Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

allocating current_user to owner of a comment

Using treehouse tuition I have build my own rails app. I've got a bit stuck at one part. I would like users to be able to add comments to each guideline (my main model). When a user adds a comment, I'd like for it to automatically say that he is the commenter. I've got completely confused about attributes etc and cannot work it out. I am now lost.

My guidelines.rb

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

user.rb

 has_many :guidelines
 has_many :favourite_guidelines
 has_many :comments

comment.rb

belongs_to :guideline
  belongs_to :commenter
  belongs_to :user

  attr_accessible :body, :commenter

the migration for the db was

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

the create action in comments_controller.rb is

def create
        @guideline = Guideline.find(params[:guideline_id])
        @comment = @guideline.comments.create(params[:comment])
        redirect_to guideline_path(@guideline)
    end

now when I try to add a new comment I get

uninitialized constant Comment::Commenter

although previously I was able to add it by input a name in the commenter field of the form. If anyone has any suggestions please let me know!

1 Answer

Jason Seifer
STAFF
Jason Seifer
Treehouse Guest Teacher

Hi Tessa!

What you probably want to do here is change the comments table very slightly. Instead of having "commenter" be a string, have it be an integer like so:

t.integer :commenter_id

Then in your comment class:

class Comment < Activerecord::Base
  belongs_to :guideline
  belongs_to :commenter, class_name: 'User', foreign_key: 'commenter_id'
end

In your controller:

def create
  @guideline = Guideline.find(params[:guideline_id])
  @comment = @guideline.comments.build(params[:comment])
  @comment.commenter = current_user
  @comment.save
  redirect_to guideline_path(@guideline)
end

That will assign the commenter to the currently logged in user. Hope that helps!