1

テーブルのクエリに問題があります。1 つのレコードのみを選択すると問題なく動作しますが、複数を選択すると動作しません。例えば

    Orders Table
      |
    / | \
OrderProducts Table
    \ | /
      |
    Products Table 

注文モデル

has_many :order_products
has_many :products, :through => :order_products

OrderProducts モデル

belongs_to :order
belongs_to :product

製品モデル

has_many :order_products
has_many :orders, :through => :order_products

アクティブレコード クエリ

Order.find(1).products // this works
Order.where(type_id:1).products // this doesn't seem to work

この方法で複数のアイテムを照会することはできませんか? この構造に基づいて別のテーブルから複数のレコードをクエリする最良の方法は何ですか?またはモデル構造を更新する必要がありますか? 私はすべての助けに感謝します! 再度、感謝します!

4

1 に答える 1

1
@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 %>
于 2013-07-16T07:05:55.923 に答える