2013-03-07 87 views
0

编辑:我创建了一个新的模型在我的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 } %> 
+0

用户如何关联评论? – jvnill 2013-03-07 12:13:03

+0

has_many:comments – tessad 2013-03-07 12:18:27

+0

删除'belongs_to:user'关联后,您还应该将其更改为'has_many:comments,:foreign_key =>'commenter_id''。 – 2013-03-07 14:39:03

回答

1

您的评论者属性是一个字符串,不起作用。迁移改成这样:

create_table :comments do |t| 
    t.references :commenter 
    # ... 
end 

此外,从您的评论模型删除belongs_to :user位,加:commenter_id而不是:commenter您attr_accessible和改变你的方式创建注释:

@comment = @guideline.comments.build params[:comment].merge(commenter_id: current_user.id) 
@comment.save 

这些后变化,它应该工作。

+0

。非常感谢 – tessad 2013-03-07 21:32:34

0
class Comment < ActiveRecord::Base 
    before_validation :current_user_makes_the_comment 

    private 
    def current_user_makes_the_comment 
     self.user_id = current_user.id 
    end 
end 

或尝试用current_user.build语法和传递guideline_idcreate方法

+0

会触发批量分配安全异常吗? – HungryCoder 2013-03-07 11:40:12

+1

这是行不通的,因为'current_user'在模型 – jvnill 2013-03-07 11:41:12

+0

中不可访问?不知道,谢谢你的信息。 – Zippie 2013-03-07 11:42:30

0

假设下面协会

# comment.rb 
belongs_to :commenter, class_name: 'User' 

试试

# controller 
@comment = @guideline.comments.create params[:comment].merge(commenter_id: current_user.id) 
+0

已经改变了上面编辑过的东西(我删除_id部分,因为没有commenter_id属性),我得到未定义的方法'active_admin_config ='为CommentsController:类 – tessad 2013-03-07 11:54:00

+0

忽略关于active_admin的消息,我解决了这个问题。当按照上面的方式编辑时(按照你的方式,但没有ID)。评论没有被正确地添加。他们以我的观点出现,因为他们被添加了,但是当我在控制台中查看准则时 - 评论是'无',所以评论。评论者也是零 – tessad 2013-03-07 12:17:16

+0

如果评论属于某个用户,您还需要将commenter_id添加到attr_accessible – jvnill 2013-03-07 12:29:21