用户和相关帖子
问题描述:
我创建了一个类似 twiiter 的应用程序,朋友可以在其中发帖,但我想要在显示所有帖子的列表中包含创建帖子的人的姓名.
I created an twiiter like app, where friends can post, but i want a include the name of the person who created the post in the list showing all the post.
这是我的代码
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
`
答
当然假设设置了'user has many posts'关联,并且用户模型有一个'username'字段,你可以在你的观点:
Assuming, of course, that the 'user has many posts' association is set, and the user model has a 'username' field, you can do this in your view :
<% @posts.each do |post| %>
<%= post.user.username %>
<% end %>