开发者

Rails has_many through filtered associations

开发者 https://www.devze.com 2023-01-24 10:59 出处:网络
I am trying to use one join model for two separate but very similar associations.Here is what I have:

I am trying to use one join model for two separate but very similar associations. Here is what I have:

Two primary models: Package, Size

Pacakges have many sizes but there's a wrinkle. Th开发者_开发技巧e sizes need to be allocated as a size for top or bottom. My current associations on Package are:

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 is a join model with: size_id | package_id | bodylocation:string

I have a failing test to verify it is working:

@p = Package.new
@size1 = Size.first
@p.tops_sizes << @size1
@p.save
@p.reload
@p.tops_sizes.should include(@size1)

This should work properly but for some reason the bodylocation field does not get automatically set.

Any ideas?


There is (IMHO) a better solution to this in the answer to: Scope with join on :has_many :through association.

Essentially it would be something like:

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

You would then query for them like:

@p.sizes.tops


Try creating two separate through associations for this.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消