Reputation: 530
Update: I just found this other thread that explains why I am having this issue ( Pass local rails variable to javascript to partial ), but it did not list out the steps to fix it (or at least it skipped too many steps that I don't yet know how to do.) The issue seems to be that the local variable being passed to the partial is no longer the same local variable that existed when new.html.erb was loaded since the partial is not loaded until the click event. Is it possible to get around that? Thanks.
Original:
I have a click event tied to a link that only works some of the time and I am not sure why. It is supposed to render a partial into my view when a link is clicked without reloading the page.
This is what I currently have (which is not working):
comps_helper.rb:
def addRound(f)
render "add_round", f: f
end
comps/new.html.erb
<div id="add_round"></div>
<%= link_to "Add round", addRoundLink_path, remote: true %>
addRoundLink.js.erb
$("#add_round").html("<%=j addRound(f) %>");
What does work:
If I just call the helper method directly from new.html.erb with <%= addRound %>, it works. But I need it to be triggered when the link is clicked so the user can add as many sections to the form as they'd like.
If the 'f' parameter is not included in the code above, the javascript does work on click. For example, if I change the partial so it just includes a string of text, it will render that text when the link is clicked. This makes me think there is an issue with how I included the 'f' parameter in the javascript. But I'm not sure why that is the case since isn't the javascript just inserting that code back into new.html.erb where I have the div with the "add_round" id?
Note: This is what I see in my javascript console when I click the link:
GET http //0.0.0.0:3000/addRoundLink 500 (Internal Server Error)
jquery.js:8215
Thanks.
Upvotes: 4
Views: 2420
Reputation: 476
It's not working because f
only exists in the context of your controller action.
When a user clicks your link, a new HTTP request is made for your javascript. The controller action handling this request is different from the one that rendered the page, so you need to set f
in this controller action and pass it as a local to addRoundLink.js.erb.
Example code
f
is determine by your model object/instance.In your controller
def add_round
model = MyModel.find params[:id]
f = model.determine_f
render :partial => 'add_round', :locals => { :f => f }
end
In your new.html.erb
<%= link_to "Add Round", add_round_path(@model), :remote => true %>
Upvotes: 3