如何在用户个人资料上呈现用户收藏的帖子?

时间:2016-11-21 22:53:58

标签: ruby-on-rails

我正在创建论坛,并且正在尝试显示当前用户在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>&nbsp; Unfavorite
 <% end %>
<% else %>
 <%= link_to [post, Favorite.new], class: 'btn btn-primary', method: :post do %>
   <i class="icon ion-ios-heart-outline"> </i>&nbsp; Favorite
 <% end %>
<% end %>

编辑: 尝试迁移到AddUserToFavorites但在rake db:migrate

时遇到迁移错误
rails g migration AddUserToFavorites user:references

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

如果要在控制中访问控制器中的变量,则必须使用@(实例变量)。因此,在您的情况下,请更新FavoritesController并使用@post = ...代替post = ...

相关问题