将评论与用户关联

时间:2014-02-05 13:38:56

标签: ruby-on-rails comments associations

我有一个允许用户评论帖子的应用程序。

rails generate model Comment commenter:string body:text post:references

如何更改,以便将commenter设置为发布评论的用户

2 个答案:

答案 0 :(得分:1)

您需要建立关联:

rails generate model Comment author_id:integer body:text post:references

class Comment < ActiveRecord::Base

  belongs_to :post
  belongs_to :author, class_name: <User or whatever your user model is called>, foreign_key: :author_id

end

class User < ActiveRecord::Base
  has_many :comments, foreign_key: :author_id
end

创建新评论时,您还需要指定此值:

#Comment controller? Hard to say how it is being saved from the code you posted. :P

  def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    if @comment.save
      ...
    end
  end

答案 1 :(得分:1)

我终于找到了解决问题的方法。

rails generate model Comment user_id:integer body:text listing:references

:user_id添加到attr_accessible文件中的\app\models\comments.rb,然后将隐藏属性添加到评论表单中:

<%= f.hidden_field :user_id, :value => current_user.id %>

然后使用<%= comment.user.id %>和/或<%= comment.user.name %>