Ruby on rails Rails activerecord有多到有多,查询全部?
我在查询一个表时遇到了一些问题,如果我只选择一条记录,它可以正常工作,但是如果我选择多条记录,它就不能工作。比如说Ruby on rails Rails activerecord有多到有多,查询全部?,ruby-on-rails,activerecord,ruby-on-rails-3.2,Ruby On Rails,Activerecord,Ruby On Rails 3.2,我在查询一个表时遇到了一些问题,如果我只选择一条记录,它可以正常工作,但是如果我选择多条记录,它就不能工作。比如说 Orders Table | / | \ OrderProducts Table \ | / | Products Table 订单模型 has_many :order_products has_many :products, :through => :order_products 订单产品模型 belongs_t
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
产品模型
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 %>
它将返回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 %>
尝试Order.where(type_id:1).first.products这与我给出的示例类似,因为我认为它只查看一条记录。我想考虑多条记录,比如说,如果type\u id返回3条记录,我想根据这3条记录查询“产品”。尝试使用Order.where(type\u id:1)。first.products这与我给出的示例类似,因为我认为它只查看一条记录。我想考虑多条记录,比如说如果type_id返回3条记录,我想根据这3条记录查询“产品”。让我知道这是否对您有帮助,如果没有帮助,我将尝试修改或删除。谢谢!正在准备手动加入表,认为有一种快速的ruby/activerecord方法可以完成此操作。如果这对您有帮助,请告诉我,如果没有帮助,我将尝试修改或删除它。谢谢!刚要手动加入表,我想会有一种快速的ruby/activerecord方法来实现这一点。