【问题标题】:How to search belongs_to association attributes如何搜索belongs_to关联属性
【发布时间】:2013-01-21 10:00:28
【问题描述】:

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

这个怎么写?

【问题讨论】:

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


    【解决方案1】:

    尝试以下方法(我更喜欢类方法而不是使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2017-08-29
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多