假设我有两个这样的模型:
class Comment < ActiveRecord::Base
belongs_to :user
named_scope :about_x :conditions => "comments.text like '%x%')"
end
class User < ActiveRecord::Base
has_many :comments
end
我想使用模型,以便我可以使用'%x%'等文本返回所有用户和所有评论
all_user_comments_about_x = User.comments.about_x
如何进行?
谢谢
答案 0 :(得分:1)
尝试以下
class User < ActiveRecord::Base
has_many :comments
named_scope :about_x, :joins => :comments, :conditions => ["comments.text like '%x%'"]
end
然后
@comments = User.about_x
答案 1 :(得分:0)
如果我理解正确,你需要
# all comments about x and the user who did it
@comments = Comment.about_x(:include => :user)
或
@user = User.first
# all @user's comments about x
@comments = @user.comments.about_x