Vendor、Item、InventoryItem の 3 つの関連モデルがあります。関連付けを利用して関連付けられた属性を返す方法を理解するのに苦労しています。
class Item < ActiveRecord::Base
has_many :inventory_items
has_many :vendors, through: :inventory_items
accepts_nested_attributes_for :inventory_items, :vendors
class InventoryItem < ActiveRecord::Base
belongs_to :item
belongs_to :vendor
class Vendor < ActiveRecord::Base
has_many :inventory_items
has_many :items, through: :inventory_items
商品を販売しているベンダーとその販売価格を返品しようとしています。これが私の SearchResults インデックス ビューです。
<table>
<tr class="search-table">
<td>Product</td>
<td>Details</td>
<td>Brand</td>
<td>Code</td>
<td>Vendors</td>
<td>Price</td>
</tr>
<% @items.each do |item| %>
<tr class="search-table">
<td><%= item.product %></td>
<td><%= item.details %></td>
<td><%= item.brand %></td>
<td><%= item.code %></td>
<td><%= #how to return vendors? %></td>
<td><%= #how to return price? %></td>
</tr>
<% end %>
</table>
ここに私の SearchResultsController があります:
class SearchResultsController < ApplicationController
def index
@search = Item.solr_search do
fulltext params[:search]
end
@items = @search.results
end
end
私はRoRに慣れていないので、どんな意見でも大歓迎です。前もって感謝します!
編集
Item.first.vendors を指定したときに Rails コンソールから返されるものを次に示します。
Item Load (0.7ms) SELECT "items".* FROM "items" LIMIT 1 Vendor Load (0.9ms) SELECT "vendors".* FROM "vendors" INNER JOIN "inventory_items" ON "vendors"."id" = "inventory_items "."vendor_id" WHERE "inventory_items"."item_id" = 1 => []
解決策の編集 モデルの関連付けにいくつかの根本的なエラーがあり、それらの関係を利用できませんでした。重複するフィールド (この場合は :item_id と :product_code) を取り除くことでこれらの関連付けをクリーンアップし、以下の回答は完全に機能しました。