tessad
tessad

Reputation: 1219

adding current_user to a comment

EDIT: I've created a new model in my rails app where users can comment on a guideline. I'd like it to automatically allocate the current_user to be the commenter. I am having real problems with working out how to allocate 'commenter' (with or without it being current_user). I am now completely confused about attributes and relationships and I would very much appreciate if someone could help

As it stands with the code below - I can't seem to allocate anything as commenter. I can create a new comment (body) but cannot seem to be able to allocate the commenter at all (its value is 'nil)

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 (model)

class Comment < ActiveRecord::Base
 belongs_to :guideline
 belongs_to :commenter, class_name: 'User'
 belongs_to :user

  attr_accessible :body, :commenter
    end

guideline.rb (model)

belongs_to :user
has_many :favourite_guidelines
has_many :comments, :dependent => :destroy

the db migration has

create_table :comments do |t|
      t.string :commenter
      t.text :body
      t.references :guideline

      t.timestamps
    end
    add_index :comments, :guideline_id

my _form has

<%= f.input :commenter %>
<%= f.input :body, label: 'Comment', as: :text, :input_html => { :cols => 200, :rows => 3 } %>

Upvotes: 0

Views: 183

Answers (3)

Jaap Haagmans
Jaap Haagmans

Reputation: 6332

Your commenter attribute is a string, that won't work. Change your migration to this:

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

Also, remove the belongs_to :user bit from your Comment model, add :commenter_id instead of :commenter to your attr_accessible and change the way you create a comment:

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

After these changes, it should work.

Upvotes: 1

jvnill
jvnill

Reputation: 29599

Assuming the following association

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

try

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

Upvotes: 0

Zippie
Zippie

Reputation: 6088

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

or try with the current_user.build syntax and pass the guideline_id in the create method

Upvotes: 0

Related Questions