ruby-on-rails - 从不同的两个带导轨的表中获取结果
问题描述
我想从不同的表中得到结果。我有 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 ...
我们怎样才能得到我想要的结果。
解决方案
我不知道这是否与您的列完全匹配,但它应该可以工作。此外,尚不清楚为什么需要加入四个表。也许我错过了一些东西。无论如何,至少可以给你一个提示。我正在使用不同的,但可以更改为您需要的任何内容。
@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 %>
推荐阅读
- json - Swift:无法读取数据,因为它的格式不正确
- aws-lambda - 使用 Amazon Lex 暂停用户
- java - 如何交换文件中两行的位置Java直接访问这些行
- eclipse - 使用 Maven 作为代理/VPN,Maven 不下载任何文件
- opencv - 告诉图书馆创建球形全景图
- java - 模块化 Spring Boot 2 应用程序导致集成测试失败
- mysql - 从另一个表返回单个记录,每个 transactionDate 有多个记录
- spring - 一个服务的多个 Spring Cloud 服务连接器
- python-3.x - psutil杀死错误的进程
- c - 编译器如何为 C 中的字符串数组分配内存?