繁体   English   中英

如何搜索belongs_to关联属性

[英]How to search belongs_to association attributes

我有两个实体, 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) ,我想编写另一个范围以搜索comments posts(msg)

这个怎么写?

尝试以下操作(与带有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM