[英]Rails activerecord has_many to has_many, query all?
我在查询表时遇到了一些麻烦,如果我只选择一个记录,它会很好地工作,但是如果我选择多个记录,它将不起作用。 例如
Orders Table
|
/ | \
OrderProducts Table
\ | /
|
Products Table
订单模型
has_many :order_products
has_many :products, :through => :order_products
订购产品型号
belongs_to :order
belongs_to :product
产品型号
has_many :order_products
has_many :orders, :through => :order_products
ActiveRecord查询
Order.find(1).products // this works
Order.where(type_id:1).products // this doesn't seem to work
这样无法查询多个项目吗? 基于此结构从另一个表查询多个记录的最佳方法是什么,或者我需要更新模型结构? 我感谢所有的帮助! 再次感谢!
@orders_ids = [1, 5, 6]
Order.where(id: @orders_ids).map{|order| order.products }
它将返回ID为1、5、6的订单的产品
在视图中实现:
在控制器动作中:
@orders_ids = [1, 5, 6]
@orders = Order.where(id: @orders_ids)
在html.erb中:
<% @orders.each do |order| %>
<%= order.number %>
<% order.products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.