【问题标题】:Putting a condition on a many-to-many query with ActiveRecord使用 ActiveRecord 对多对多查询设置条件
【发布时间】:2009-12-10 23:39:08
【问题描述】:

我的模型中有以下关系:

class Show < ActiveRecord::Base
  has_many :service_shows
  has_many :services, :through => :service_shows
end

class Service < ActiveRecord::Base
  has_many :service_shows
  has_many :shows, :through => :service_shows
end

class ServiceShow < ActiveRecord::Base
  belongs_to :show
  belongs_to :service
end

我想查询具有 rec_status = 'A' 的给定服务的所有节目,但我的 ActiveRecord 技能只有大约 3 天,所以我不太有能力。如果我理解正确,我可以简单地调用 service.shows 并过滤返回的列表,但我只想从数据库中检索我需要的记录——我不想在我没有的记录上浪费处理器时间和内存'不想。

谢谢!

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord


    【解决方案1】:

    根据您的描述,听起来节目有:rec_status 列。在此基础上,我设置了一些示例数据:

    Show.create!(:name => 'One', :rec_status => 'A')
    Show.create!(:name => 'Two', :rec_status => 'B')
    
    Service.create!(:name => 'Service One')
    Service.create!(:name => 'Service Two')
    
    Show.first.services = Service.all
    Show.last.services = Service.all
    

    正如您所提到的,只要提供一项服务,您就可以取回所有节目:

    service = Service.first
    service.shows
    

    如果要选择记录子集,可以使用查找器调用扩展链:

    service.shows.all(:conditions => {:rec_status => 'A'})
    

    更好的是,您可以将其捕获为 Show 模型上的命名范围:

    class Show < ActiveRecord::Base
      has_many :service_shows
      has_many :services, :through => :service_shows
    
      named_scope :for_status, lambda {|status_flag| {:conditions => {:rec_status => status_flag}} }
    end
    

    然后使用它而不是传递:conditions 哈希:

    service.shows.for_status('A')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2023-03-12
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多