我即将为我的食谱类建立一个类似的机器。
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
配方/ 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 %>
喜欢/ destroy.js.erb
$("#like_form").html("<%= escape_javascript(render('recipes/like')) %>")
喜欢/ update.js.erb
$("#like_form").html("<%= escape_javascript(render('recipes/unlike')) %>")
配方/ _unlike.html.erb
<%= form_for @like, :html => { :method => :delete },
:remote => true do |f| %>
<%= f.submit "Unlike" %>
<% end %>
配方/ _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 %>
点击“不喜欢”后,应该渲染“喜欢”按钮。但是我不知道如何在_like.html partial中创建form_for参数。
我不知道如何获取recipe.id的值。如何在_like.html.erb中使用recipe.id?
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'
答案 0 :(得分:0)
修复它:
_like.html.erb
<% if like = current_user.likes.find_by_recipe_id(@recipe.id) %>
<% else %>
<%= form_for current_user.likes.build(:recipe_id => @recipe.id), :remote => true do |f| %>
<%= f.hidden_field :recipe_id %>
<%= f.hidden_field :user_id %>
<%= f.submit "Like" %>
<% end %>
<% end %>