First, I have a polymorphic association setup because comments can belong to any object(in my case post and articles).
I want to be able to say:
u = user.first
u.comments #This will list all comments from a user
u.comments.where(:commentable_type => "Post")
This above line doesn’t work. it generates a sql:
SELECT “comments”.* FROM “comments” WHERE “comments”.”commentable_id” = 1 AND “comments”.”commentable_type” = ‘User’ AND “comments”.”commentable_type” = ‘Post’
obviously this would return an empty list because a comment can’t belong to 2 types. I also want to be able to say:
f = Food.first
f.comments.first.user #give me the user that posted the first comment
Here’s my basic model… any tips on changing this?
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class User < ActiveRecord::Base
has_many :comments, :as => :commentable
end
I think you should review your comment model, it should look like:
So you’d have two relationships, the first will point to who posted the comment, the other will point to the object being commented.
Dont forget the migrations if you wish to try this approach.