0

我有两个实体PostsComments关联如下

class Post < ActiveRecord::Base
  attr_accessible :title, :msg
  has_many :comments
end

class Comment < ActiveRecord::Base
  attr_accessible :msg
  belongs_to :post
  scope :search, lambda { |msg| where(arel_table[:msg].matches('%#{msg}%'))}
end

现在scope :search只搜索,comments(msg)我想写另一个范围来搜索posts(msg)comments

这个怎么写?

4

1 回答 1

0

尝试以下方法(我更喜欢类方法而不是 lambda 作用域,因为它们看起来更干净且更易于阅读)

# comment.rb

def self.search(msg)
  where(arel_table[:msg].matches('%#{msg}%'))
end

def self.post_search(msg)
  joins(:post).where(Post.arel_table[:msg].matches("%#{msg}%"))
end
于 2013-02-06T09:18:17.180 回答