Question

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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top