Rails has_many具有直接和间接关联

时间:2015-10-07 18:20:24

标签: ruby-on-rails ruby activerecord database-design

我有三种型号:分类,线和产品。

类别有行。
Line有产品。
而且产品也可以直接属于Category。

所以我有两种关联变体:

1 - Category -> Line -> Product
2 - Category -> Product

如何使用has_many实现此目的?

当然,我不能像这样声明两个has_many

# category.rb
has_many :lines
has_many :products, through: :lines
has_many :products

2 个答案:

答案 0 :(得分:3)

你应该这样设置:

has_many :lines
has_many :line_products, through: lines, source: products
has_many :products

使用:source,我们告诉Rails在Line模型上查找名为:products的关联并使用它。

您还可以查看http://guides.rubyonrails.org/association_basics.html#has-many-association-reference以获取更多信息。

答案 1 :(得分:0)

我假设我们正在尝试构建一个看起来像这样的查询:

SELECT * FROM products
  LEFT OUTER JOIN lines ON products.line_id = lines.id
  WHERE lines.category_id = <category_id> 
    OR products.category_id = <category_id>;

Category中,我们可以创建实例方法而不是使用关联:

class Category < ActiveRecord::Base
  def products
     Product.eager_load(:line)
      .where("products.category_id = :id OR lines.category_id = :id", {id: id})
  end
end

但如果协会确实是你的事情,那么这样的事情可能有用(我不是100%肯定):

class Category < ActiveRecord::Base
  has_many :products, ->(category) { 
    reset.eager_load(:line)
      .where("products.category_id = :id OR lines.category_id = :id", {id: category.id})
  }
end