首页 > 解决方案 > 从不同的两个带导轨的表中获取结果

问题描述

我想从不同的表中得到结果。我有 4 张桌子。像这样:: 产品、类别、区域、product_categoriesProduct.joins(:product_categories, :categories, :regions).includes(product_categories: [:region]).includes(product_categories: [:categories]).where("product_categories.region_id = 1").select("product.name, category.name").group("product.name, category.name")

我正在使用 has_many :通过协会

结果必须是 product_name , category_name

1- Computer, Furniture 
2- Computer, Tools
3- Computer, Gadgets 
4- Mouse, Gadgets
5- Mouse, Tools 

但我得到了像这样的产品模型

1- Computer, computer_id ....
2- computer, computer_id ...

我们怎样才能得到我想要的结果。

标签: ruby-on-railshas-many-through

解决方案


我不知道这是否与您的列完全匹配,但它应该可以工作。此外,尚不清楚为什么需要加入四个表。也许我错过了一些东西。无论如何,至少可以给你一个提示。我正在使用不同的,但可以更改为您需要的任何内容。

@products =
  Product.joins(:categories, :product_categories)
  .select('products.name AS product_name, categories.name AS category_name, product_categories.region_id')
  .where('product_categories.region_id = 1')
  .distinct


<% @products.each do |product| %>
  <p><%= product.product_name %> | <%= product.category_name %></p>
<% end %>

推荐阅读