Question

I'm sure this is simple, I just haven't grasped it yet...

I have a big div that I want the user to click it and it will send him to it the model he clicked (like in SO, but clicking anywhere on the question div will redirect to the question)

<% @questions.each do |question| %>
<div id="question-<%= question.id%>" >
.... question details here ... not important to the question
</div>
<% end %>

now, before I would use on-click="window.location = '<%= question_path(question) %>'" so for each question I will get the apprpriate url for when the div is clicked.

I'd like to change this with jquery (in a separate file)

question.js.erb:

$(function() {
    $([id^="question-"]).bind("click", function() {
      window.location = <%= question_path(question) %>
    });
});

and that's exactly my problem.. the JS file doesn't know what question is, since its a variable in the each loop.

is there a way to pass information to the JS so I can use it to generate the correct path?

The solution that was implemented, with the advice of Rahul garg is to make an html5 data- attribute

<div id="question-<%= question.id%>" data-questionurl= '<%= question_path(question) %>'>

and then in the js do

window.location = this.getAttribute("data-questionurl");

I hope this solution is good coding practice

Was it helpful?

Solution

.erb file is processed once when it is rendered to the page.

All the path helpers are available so just once, you can't call a rails helper(or any other rails code) from client side unless you made a separate ajax call.

So, In this case your options are:

  • Store the path in some attr in the #question div itself and fetch it in js function.
  • Store path in js array/hash , maintain them and use it appropriately
  • Modify your routes to have questions_path as collection instead of on member like /question?id=5 instead of question/5/, in that case you can add query parameter id in your js function your self and questions_path will return you /question
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top