I'm having some trouble querying through a table, it works fine if I select only one record, but If I select multiple it doesn't work. For example
Orders Table
|
/ | \
OrderProducts Table
\ | /
|
Products Table
Orders model
has_many :order_products
has_many :products, :through => :order_products
OrderProducts model
belongs_to :order
belongs_to :product
Products model
has_many :order_products
has_many :orders, :through => :order_products
Activerecord queries
Order.find(1).products // this works
Order.where(type_id:1).products // this doesn't seem to work
Is it not possible to query multiple items in this manner? What would be the best way to go about querying multiple records from another table based on this structure or would I need to update my model structure? I appreciate all the help! Thanks again!
@orders_ids = [1, 5, 6]
Order.where(id: @orders_ids).map{|order| order.products }
it will return products for Order with id 1, 5, 6
implement this in a view:
in controller action:
@orders_ids = [1, 5, 6]
@orders = Order.where(id: @orders_ids)
in html.erb:
<% @orders.each do |order| %>
<%= order.number %>
<% order.products.each do |product| %>
<%= product.name %>
<% end %>
<% end %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.