我正在创建论坛,并且正在尝试显示当前用户在users/show.html.erb
视图中收藏的帖子列表。
当我最喜欢的帖子,然后转到我的用户个人资料显示页面时,我的app/views/favorites/_favorite.html.erb
中出现以下错误:
NameError in Users#show
undefined local variable or method `post'
<% if favorite = current_user.favorite_for(post) %>
我错过了favorites_controller.rb
中阻止其保存的内容,然后将其呈现为列表?或者我是否在users/show.html.erb
视图中不正确地呈现它?
这是我的favorites_controller.rb
:
class FavoritesController < ApplicationController
before_action :require_sign_in
def create
post = Post.find(params[:post_id])
favorite = current_user.favorites.build(post: post)
if favorite.save
flash[:notice] = "Saved as favorite!"
else
flash[:alert] = "Favorite failed to save."
end
redirect_to [post.topic, post]
end
def destroy
post = Post.find(params[:post_id])
favorite = current_user.favorites.find(params[:id])
if favorite.destroy
flash[:notice] = "Post unfavorited."
else
flash[:alert] = "Unfavoriting failed."
end
redirect_to [post.topic, post]
end
end
以下是我在users/show.html.erb
中的呈现方式:
<h2>Favorites</h2>
<%= render @user.favorites %>
<h2>Posts</h2>
<%= render @user.posts %>
还为users/show.html.erb
尝试了此操作:
<h2>Favorites</h2>
<%= render partial: @user.favorites %>
这是我的favorites/_favorite.html.erb
(排名第一的问题):
<% if favorite = current_user.favorite_for(post) %>
<%= link_to [post, favorite], class: 'btn btn-danger', method: :delete do %>
<i class="icon ion-ios-heart"> </i> Unfavorite
<% end %>
<% else %>
<%= link_to [post, Favorite.new], class: 'btn btn-primary', method: :post do %>
<i class="icon ion-ios-heart-outline"> </i> Favorite
<% end %>
<% end %>
编辑:
尝试迁移到AddUserToFavorites但在rake db:migrate
rails g migration AddUserToFavorites user:references
感谢您的帮助。
答案 0 :(得分:3)
如果要在控制中访问控制器中的变量,则必须使用@
(实例变量)。因此,在您的情况下,请更新FavoritesController
并使用@post = ...
代替post = ...