我的模型中有以下关系:
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并过滤返回的列表,但我只想从数据库中检索我需要的记录--我不想把处理器时间和内存浪费在我不想要的记录上。
谢谢!
发布于 2009-12-11 09:27:15
从您的描述中,听起来像是有: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如果要选择记录的子集,可以使用finder调用来扩展链:
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')https://stackoverflow.com/questions/1884899
复制相似问题