编辑:我创建了一个新的模型在我的rails应用程序中,用户可以在指南上发表评论。我希望它自动分配current_user作为评论者。我正在解决如何分配'评论者'(带或不带current_user)的实际问题。我现在完全对属性和关系感到困惑,我非常感谢如果有人可以帮助将current_user添加到评论
由于它代表下面的代码 - 我似乎无法分配任何作为评论者。我可以创造一个新的评论(身体),但似乎没有能够在所有分配评议(它的值是“无)
comments_controller.rb
def create
@guideline = Guideline.find(params[:guideline_id])
@comment = @guideline.comments.create params[:comment].merge(commenter: current_user)
redirect_to guideline_path(@guideline)
end
comment.rb(模型)
class Comment < ActiveRecord::Base
belongs_to :guideline
belongs_to :commenter, class_name: 'User'
belongs_to :user
attr_accessible :body, :commenter
end
guideline.rb(模型)
belongs_to :user
has_many :favourite_guidelines
has_many :comments, :dependent => :destroy
分贝迁移具有
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :guideline
t.timestamps
end
add_index :comments, :guideline_id
我_form有
<%= f.input :commenter %>
<%= f.input :body, label: 'Comment', as: :text, :input_html => { :cols => 200, :rows => 3 } %>
用户如何关联评论? – jvnill 2013-03-07 12:13:03
has_many:comments – tessad 2013-03-07 12:18:27
删除'belongs_to:user'关联后,您还应该将其更改为'has_many:comments,:foreign_key =>'commenter_id''。 – 2013-03-07 14:39:03