Ruby on rails 在rails中加入多个

Ruby on rails 在rails中加入多个,ruby-on-rails,join,associations,has-many-through,has-many,Ruby On Rails,Join,Associations,Has Many Through,Has Many,我有以下三种型号 class Order belongs_to :item belongs_to :category end class Item has_many :orders belongs_to :category end class Category has_many :items has_many :orders, through: :items end 我想加入表,如Order.joins(:item).joins(:category),但它不起作用 所需的SQL

我有以下三种型号

class Order
 belongs_to :item
 belongs_to :category
end

class Item
 has_many :orders
 belongs_to :category
end

class Category
 has_many :items
 has_many :orders, through: :items
end
我想加入表,如
Order.joins(:item).joins(:category)
,但它不起作用

所需的SQL是

SELECT * FROM `orders` 
INNER JOIN `items` ON `items`.`id` = `orders`.`item_id` 
INNER JOIN `categories` ON `items`.`category_id` = `categories`.`id`

我希望你能帮上忙。

你要找的语法是

Order.joins(item: :category)

查看更多信息。

您要查找的语法是

Order.joins(item: :category)

查看更多信息。

我有点困惑,因为订单和项目都属于类别,而且类别已经有了很多订单,通过设置,
:through
选项是不必要的

对于所需的输出,我猜您希望执行嵌套联接(订单>项目>类别),而不是多个联接(订单>项目+类别)

12.1.3.1加入嵌套关联(单级) 文章加入(评论::嘉宾)

这将产生:

从文章中选择文章。* comments.article\u id=articles.id上的内部联接注释 在guests.comment\u id=comments.id上内部加入来宾


因此,您应该执行类似于“订单.连接(项目::类别)

的操作。我有点困惑,因为订单和项目都属于类别,而类别在该设置中已经有很多订单,
:through
选项是不必要的

对于所需的输出,我猜您希望执行嵌套联接(订单>项目>类别),而不是多个联接(订单>项目+类别)

12.1.3.1加入嵌套关联(单级) 文章加入(评论::嘉宾)

这将产生:

从文章中选择文章。* comments.article\u id=articles.id上的内部联接注释 在guests.comment\u id=comments.id上内部加入来宾


因此,您应该执行类似于“Order.joins”(item::category)的操作设置这些关联的正确方法是:

class Order < ApplicationRecord
  belongs_to :item
  # This references items.category_id
  has_one :category, through: :item
end

class Item < ApplicationRecord
  has_many :orders
  belongs_to :category
end

class Category < ApplicationRecord
  has_many :item, through: :orders
  has_many :orders
end
如您所见,Rails将自动处理联接表(项目)的联接

如果希望加载两个关联,可以使用哈希或仅列出两者:

Order.eager_load(item: :category) 
Order.eager_load(:item, :category)

设置这些关联的正确方法是:

class Order < ApplicationRecord
  belongs_to :item
  # This references items.category_id
  has_one :category, through: :item
end

class Item < ApplicationRecord
  has_many :orders
  belongs_to :category
end

class Category < ApplicationRecord
  has_many :item, through: :orders
  has_many :orders
end
如您所见,Rails将自动处理联接表(项目)的联接

如果希望加载两个关联,可以使用哈希或仅列出两者:

Order.eager_load(item: :category) 
Order.eager_load(:item, :category)
谢谢Order.joins(项目::类别)运行良好。谢谢。Order.joins(item::category)运行良好。