mhz
mhz

Reputation: 1029

Dealing with Comments in Ruby on Rails

Currently, I'm making a simple blog-like app, where a user can make a post, and several other users can comment on it.

Is there a way to have a polymorphic attribute belong to more than one Model?

For example,

a Comment will always have an author (User model) However, a Comment can belong to many other models (Posts, Journals, Articles, etc etc)

so, for (Posts, Journals, Articles) models, polymorphic association is best. However, for the author (or User relationship), polymorphic would not work, since polymorphic can only belong to one at a time.

Is there a better way around this?

EDIT: What are the pros/cons of doing this:

class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :commentable, :polymorphic => true
end

EDIT2: with the solution above, is there a more elegant way of doing this

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.user_id = current_user.id

    if @comment.save
        flash[:success] = 'Comment created'
        redirect_to @commentable
    else
        flash[:error] = 'Comment not created - is body empty?'
        redirect_to @commentable
    end
end

without having to save the user_id manually in the controller?

    @comment.user_id = current_user.id

Upvotes: 0

Views: 107

Answers (1)

Marc Baumbach
Marc Baumbach

Reputation: 10473

You can have both a User relationship as well as a polymorphic relationship representing the model it is associated with. For example:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :document, polymorphic: true
end

class Post < ActiveRecord::Base
  has_many :comments, as: :document
end

class Journal < ActiveRecord::Base
  has_many :comments, as: :document
end

class Article < ActiveRecord::Base
  has_many :comments, as: :document
end

class User < ActiveRecord::Base
  has_many :comments
end

Now, you can call comment.user to get the User model for the person who created the comment and comment.document to get the Post, Journal, or Article that the comment is associated with.

Upvotes: 1

Related Questions