2012-04-08 69 views
0

我创建了一个类似于应用程序的twiiter,朋友可以在其中发帖,但是我想要在显示所有帖子的列表中包含创建帖子的人员的姓名。用户及相关文章

这里是我的代码

class PostsController < ApplicationController 
    def index 
    @posts = Post.all(:order => "created_at DESC") 

    respond_to do |format| 
     format.html 
    end 
    end 

    def create 
    @post = Post.create(:message => params[:message]) 

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to posts_path } 
     format.js 
     else 
     flash[:notice] = "Message failed to save." 
     format.html { redirect_to posts_path } 
     end 
    end 
    end 
end 
` 

回答

1

假设,当然,前提是“用户有很多帖子协会设置,用户模式有一个“用户名”字段中,您可以在您的视图做到这一点:

<% @posts.each do |post| %> 
    <%= post.user.username %> 
<% end %> 
+0

它拥有所有你说的,但我得到的错误消息'未定义的方法'用户名”的零:NilClass'我是否需要将任何东西在岗控制器 – 2012-04-08 10:20:41

+0

这意味着,您的文章没有连接给特定的用户,因此该关联是零。为避免发生错误,您可以将该行更改为'<%= post.user.try(:username)%>' – Spyros 2012-04-08 10:29:04

+0

'<%= div_for post do%>

<%= time_ago_in_words(post.created_at) %>前

<%= post.message%>

<% end %>' – 2012-04-08 10:32:26