0

我创建了一个类似推特的应用程序,朋友可以在其中发帖,但我希望在显示所有帖子的列表中包含创建帖子的人的姓名。

这是我的代码

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
`
4

1 回答 1

1

当然,假设设置了“用户有很多帖子”关联,并且用户模型有一个“用户名”字段,您可以在视图中执行此操作:

<% @posts.each do |post| %>
  <%= post.user.username %>
<% end %>
于 2012-04-08T10:05:39.577 回答