在Rails中查询关联的表

时间:2018-09-25 14:00:16

标签: ruby-on-rails ruby-on-rails-5

所以我正在努力了解红宝石。我有3个带有以下关联的表。我想查询产品表上的所有项目以及每个产品的关联数据。

例如,我想在我的react组件中渲染:

产品名称来自产品表

产品UPC 来自产品表

日期来自产品表

的产品

属性名称(例如材料)来自属性表

属性值(例如棉花)来自product_property表

class Property < ApplicationRecord
  has_many :product_properties
  has_many :products, through: :product_properties
  accepts_nested_attributes_for :product_properties
end

class Product < ApplicationRecord
  has_many :product_properties
  has_many :properties, through: :product_properties
end

class ProductProperty < ApplicationRecord
  belongs_to :property, required: false
  belongs_to :product, required: false
end

现在,我了解使用以下方法获取所有产品

Product.all

我不了解的是如何获得每个产品以及相关的属性和产品属性。

我可以看到here在其中使用此方法的地方,但是我无法实现。

Author.joins(:articles).where(articles: { author: author })

谢谢您能给我的帮助。

1 个答案:

答案 0 :(得分:1)

对于急切加载,通常应使用

Product.includes(:properties)

但是,ActiveRecord使用的一般方法是使用单独的查询来加载关联数据,从而导致这些查询:

> products = Product.includes(:properties).to_a
  Product Load (0.2ms)  SELECT "products".* FROM "products"
  ProductProperty Load (0.2ms)  SELECT "product_properties".* FROM "product_properties" WHERE "product_properties"."product_id" = ?  [["product_id", 1]]
  Property Load (0.2ms)  SELECT "properties".* FROM "properties" WHERE "properties"."id" = ?  [["id", 1]]
 => [#<Product id: 1, name: "product">] 
> products.first.properties.to_a
 => [#<Property id: 1, name: "property">] 

如果您知道记录只能用一个查询加载,则可以使用

Product.eager_load(:properties)

将翻译为

SELECT "products"."id" AS t0_r0, "products"."name" AS t0_r1, "properties"."id" AS t1_r0, "properties"."name" AS t1_r1 FROM "products" LEFT OUTER JOIN "product_properties" ON "product_properties"."product_id" = "products"."id" LEFT OUTER JOIN "properties" ON "properties"."id" = "product_properties"."property_id"