ruby-on-rails Rails habtm连接

olhwl3o2  于 4个月前  发布在  Ruby
关注(0)|答案(2)|浏览(54)

我在类别、产品和品牌之间有这样的关系:

class Brand < ActiveRecord::Base
  has_many :products
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
  belongs_to :brand
end

字符串
我怎么能选择所有类别的指定品牌与此关系?我尝试这一点,但得到一个错误

b = Brand.find(1)
Category.joins(:products).where(:products => b.products)

2ledvvac

2ledvvac1#

你对join做了正确的事情,只是添加了一个更复杂的where定义:

Category.joins(:products).where(:products => {:brand_id => 1})

字符串

rt4zxlrg

rt4zxlrg2#

有争议的是,HABTM很少是一个好的设计,而IMO几乎是Rails唯一出错的地方。
引入一个外部参照表来连接产品和类别,并在关系的两端使用has_many:through,因此最终得到

class Brand < ActiveRecord::Base
  has_many :products
  has_many :categories, :through => :products # This is now allowed in Rails 3.x and above
end

class Category < ActiveRecord::Base
  belongs_to :product_category
  has_many :products, :through => :product_category 
end

class Product < ActiveRecord::Base
  belongs_to :brand
  belongs_to :product_category
  has_many :categories, :through => :product_category
end

class ProductCategory < ActiveRecord::Base
  has_many :products
  has_many :categories
end

字符串
这为您提供了最大的灵活性,使您只需进行最少的代码重构,并提供了一条更直观的路径来获取关系中任何一方所需的任何数据,并使您能够实现以下目标

b = Brand.find(1)
b.categories.all

更新以上是完全未经测试的代码,我刚刚纠正了一个愚蠢的错误,我做了。如果你有任何问题,实现这一点,然后回来

相关问题