在“索引”页面上显示帖子+海报的信息

时间:2011-08-01 01:13:39

标签: ruby-on-rails ruby

我想在我的rails应用程序上显示帖子以及海报的信息。现在我可以在“显示”页面(单个帖子的页面)上显示帖子和用户关联,但是当我想在“索引”页面(我的所有帖子都在哪里)上显示它时,我收到此错误: nil的未定义方法`username':NilClass

我在“show”下将 @ post.user = current_user 添加到我的post_controller(这让我可以显示海报的信息。但我不知道要添加到“def index”中的内容。< / p>

这就是我的意思:

  def index
    @posts = Post.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

这就是我在“show”下的内容

 def show
    @post = Post.find(params[:id])
    @post.user = current_user
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

我想知道要添加到我的def索引中的内容,以便能够显示海报的信息。提前谢谢。

1 个答案:

答案 0 :(得分:2)

你的设置错了。用户需要在创建和更新时添加到帖子中。 正如您现在所看到的,所有帖子将始终属于当前正在查看帖子的用户,因为您正在将show_user分配给show动作中的帖子(如果您继续使用此方法,则会在索引视图中执行相同操作)意味着当用户1查看帖子1时,它将显示为属于用户1.当用户2显示帖子1时,它将属于用户2。

解决方案是将当前用户分配给更新中的帖子并创建帖子控制器的操作,就像现在在show动作中但在帖子物理更新或创建之前一样。

然后从show动作中删除@ post.user = current_user。 这可能意味着您的应用中没有分配用户的遗留数据。但那就是o.k.,只需编辑并保存每个帖子,它就会自动附加。

然后在views / posts / index_html.erb中,只需在显示/编辑链接之前添加要在新表行列中查看的用户详细信息。这假设您有一个标准的scaffolded index.html.erb文件。如果你没有标准索引视图,那么把它放在你想要的任何地方,但是如果你有一个自定义的索引视图,你可能不会首先问这个问题所以忘了这个,你就知道它在哪里去

<强>更新

我在上面的回复中解释了如何在视图中显示用户,但我可能需要更清楚一些,所以我会告诉你代码。 要在节目视图中显示用户名,请使用

<%= @post.user.name unless @product.user.blank? %>

在后期使用的索引操作中显示用户

<% @posts.each do |post| %> <!-- This is already in your index action. -->
  <%=post.user.name unless post.user.blank?%><!-- This is the code you need -->
  <!-- You might want to add a new th in the header for the css table then you can add a <td></td> tags round the above line so your table all matches up nicely for display purposes-->
<%end%> <!-- This is already in your index action -->

希望有所帮助