I'm about to build a like machinery for my recipe class.
class LikesController
def update
@like = Like.find(params[:id])
end
def destroy
@like = Like.find(params[:id])
@recipe = Recipe.find(params[:id])
@like.destroy
end
end
def show
@recipe = Recipe.find(params[:id])
end
recipes/show.html.erb
<div id="like_form">
<% if like = current_user.likes.find_by_recipe_id(@recipe.id) %>
<%= form_for like, :html => { :method => :delete },:remote => true do |f| %>
<%= f.submit "Unlike" %>
<% end %>
<% else %>
<%= form_for current_user.likes.create(:recipe_id => @recipe.id), :remote => true do |f| %>
<%= f.hidden_field :recipe_id %>
<%= f.hidden_field :user_id %>
<%= f.submit "Like" %>
<% end %>
<% end %>
likes/destroy.js.erb
$("#like_form").html("<%= escape_javascript(render('recipes/like')) %>")
likes/update.js.erb
$("#like_form").html("<%= escape_javascript(render('recipes/unlike')) %>")
recipes/_unlike.html.erb
<%= form_for @like, :html => { :method => :delete },
:remote => true do |f| %>
<%= f.submit "Unlike" %>
<% end %>
recipes/_like.html.erb
<%= form_for current_user.likes.create(:recipe_id => @recipe.id), :remote => true do |f| %>
<%= f.hidden_field :recipe_id %>
<%= f.hidden_field :user_id %>
<%= f.submit "Like" %>
<% end %>
After clicking on "Unlike", the "Like" button should be rendered. But I've no idea how to make the form_for argument in the _like.html partial.
I don't know how to get the value for recipe.id. How can I make recipe.id available in _like.html.erb?
ActionView::Template::Error (undefined method `id' for nil:NilClass):1:
<%= form_for current_user.likes.create(:recipe_id => @recipe.id),
:remote => true do |f| %>
2: <%= f.hidden_field :recipe_id %>
3: <%= f.hidden_field :user_id %>
4: <%= f.submit "Like" %>
app/views/recipes/_like.html.erb:1:in
_app_views_recipes__like_html_erb___1003281063_65806008'
app/views/likes/destroy.js.erb:1:in
_app_views_likes_destroy_js_erb___41116873_65874912'
fixed it with:
_like.html.erb