如何搜索belongs_to关联属性

时间:2013-02-06 09:01:19

标签: ruby-on-rails ruby-on-rails-3 scope arel rails-activerecord

我有两个实体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

如何写这个?

1 个答案:

答案 0 :(得分:0)

尝试以下方法(我喜欢类方法,而不是使用lambdas的范围,因为它们看起来更干净,更容易阅读)

# 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