Reputation: 989
I'm rendering a partial viewer
using ajax and jQuery. I want to set a variable within the partial, based on the link that is clicked on.
ERB:
<%=link_to "link1", viewer_path(id: Painting.first), remote: true%>
<%=link_to "link2", viewer_path(id: Painting.last), remote: true%>
Controller:
def viewer
@painting = Painting.find_by(:id)
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
viewer.js.erb
$("#viewer").html("<%= escape_javascript(render 'viewer') %>");
_viewer.html.erb
<%= @painting.name %>
But the variable @painting
isn't set when the partial is rendered so I get an error.
Shouldn't defining the variable in the controller have the value carry though to the partial? What am I doing wrong?
Upvotes: 0
Views: 31
Reputation: 10029
This may be your problem: when using Model.find_by
, you need to specify what you are finding by. Try using Model.find
, which always uses the Model's :id
, or Model.find_by_id
or Model.find_by(id: :id)
.
Make this update in controller#viewer:
@painting = Painting.find(:id)
You are right though, instance variables (@painting
) are usable in partials.
Upvotes: 1