2009-12-10 103 views
1

我有我的模型以下关系:把一个条件在许多一对多查询用ActiveRecord

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技能只有三天左右的时间,所以我没有那么好。如果我理解正确,我可以简单地调用service.shows并筛选返回的列表,但我只想从数据库中检索我需要的记录 - 我宁愿不浪费处理器时间和记录上的记录,不想要。

谢谢!

回答

6

从您的描述来看,这听起来像是节目有: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'}) 

更重要的是,你可以捕捉到这些作为显示模式名为范围:

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')