Rails has_many通过过滤的关联
问题描述:
我想为两个单独但非常相似的关联使用一个连接模型。以下是我有:Rails has_many通过过滤的关联
两个主要型号有:包装,尺寸
Pacakges有多种尺寸,但有皱纹。尺寸需要分配为顶部或底部的尺寸。我的包目前协会有:
has_many :package_sizes
has_many :sizes, :through => :package_sizes
has_many :bottoms_sizes, :through => :package_sizes, :scope => {:package_sizes => {:bodylocation => "B"}}, :source => :size
has_many :tops_sizes, :through => :package_sizes, :scope => {:package_sizes => {:bodylocation => "T"}}, :source => :size
包装尺寸与联接模型:size_id | package_id | bodylocation:字符串
我有一个失败的测试,以验证它是否工作:
@p = Package.new
@size1 = Size.first
@p.tops_sizes << @size1
@p.save
@p.reload
@p.tops_sizes.should include(@size1)
这应该正常工作,但由于某种原因,bodylocation场不会被自动设置。
任何想法?
答
尝试为此创建两个单独的直通关联。
has_many :bottom_package_sizes, :class_name => 'PackageSize', :conditions => {:bodylocation => 'B'}
has_many :top_package_sizes, :class_name => 'PackageSize', :conditions => {:bodylocation => 'T'}
has_many :bottom_sizes, :through => :bottom_package_sizes
has_many :top_sizes, :through => :top_package_sizes
答
有(恕我直言)较好地解决了这个在回答:Scope with join on :has_many :through association。
本质上,它会是这样的:
has_many :package_sizes
has_many :sizes, :through => :package_sizes do
def tops
where("package_sizes.bodylocation = 'T'")
end
def bottoms
where("package_sizes.bodylocation = 'B'")
end
end
然后,您可以查询他们喜欢:
@p.sizes.tops
真棒。很棒。谢谢! – chrishomer 2010-11-12 02:30:34