0

I was following RyanB's polymorphic association video which shows examples of implementing a comment system.

http://railscasts.com/episodes/154-polymorphic-association-revised?autoplay=true

I was wondering how do I add a username into the database of the person that is creating the new comment? This way I can display username in the view pages,

Thanks

hellomello
  • 8,219
  • 39
  • 151
  • 297

1 Answers1

5

Too many ways to do it

Solution 1

If you will using authentication for comment system you should add one model user for authentication (suggest to use devise)

class User < ActiveRecord::Base
  attr_accessible :email, :password, :username
  has_many :comments
end


class Comment < ActiveRecord::Base
 attr_accessible :content, :user_id
 belongs_to :commentable, polymorphic: true
 belongs_to :user
end

and on controller (take from repository of 154-polymorphic-association-revised )

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.user_id = current_user.id
    if @comment.save
     redirect_to @commentable, notice: "Comment created."
    else
     render :new
    end
end

OR Solution 2

You just add one attribute to comment model (without authentication)

   class Comment < ActiveRecord::Base
     attr_accessible :content, :username
     belongs_to :commentable, polymorphic: true
   end
rails_id
  • 8,120
  • 4
  • 46
  • 84
  • What does the @comment.user = current_user mean? I am using devise. Right now, I'm displaying comment content like this `<%= simple_format comment.content %>`, how do I add on so I can do something like `comment.username`? Thanks for your help! I really appreciate it! – hellomello Jun 07 '13 at 05:42
  • Sorry, I mean like this `@comment.user_id = current_user.id`, That is automatically store `user_id` in column of comments. If you want display username (user attribute), you just calling username such as `<%= comment.user.username %>` – rails_id Jun 07 '13 at 05:58
  • When I tried putting @comment.user_id I get a `undefined method `user_id=' for #` error? – hellomello Jun 08 '13 at 00:24
  • Thanks, this actually helped me get to the right path, and I believe, your first syntax was correct, `@comment.user_id = current_user` – hellomello Jun 08 '13 at 01:52