用户和相关帖子 [英] User and associated Post

查看:41
本文介绍了用户和相关帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类似 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 %>

这篇关于用户和相关帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆