首先,我有一个多态关联设置,因为评论可以属于任何对象(在我的例子中是帖子和文章)。
我想能够说:
u = user.first
u.comments #This will list all comments from a user
u.comments.where(:commentable_type => "Post")
上面这行不起作用。它生成一个 sql: SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = 1 AND "comments"."commentable_type" = 'User' AND "comments"."commentable_type" = 'Post'
显然这将返回一个空列表,因为评论不能属于 2 种类型。我也想能够说:
f = Food.first
f.comments.first.user #give me the user that posted the first comment
这是我的基本模型......关于改变这个的任何提示?
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