Rails has_many通过过滤的关联

时间:2010-11-12 00:44:07

标签: ruby-on-rails ruby-on-rails-3 associations

我试图将一个连接模型用于两个独立但非常相似的关联。这就是我所拥有的:

两个主要模型:包装,尺寸

Pacakges有很多尺寸,但有皱纹。尺寸需要分配为顶部或底部的尺寸。我目前在Package上的关联是:

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

PackageSize是一个连接模型: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字段不会自动设置。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

(IMHO)在答案中有一个更好的解决方案: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

答案 1 :(得分:1)

尝试为此创建两个单独的直通关联。

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