I have three relevant models: Vendor, Item, InventoryItem. I'm having difficulty understanding how to tap into associations to return associated attributes.
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
I'm trying to return the vendors who sell an item, and the price they sell it for. Here's my SearchResults index view:
<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>
Here is my SearchResultsController:
class SearchResultsController < ApplicationController
def index
@search = Item.solr_search do
fulltext params[:search]
end
@items = @search.results
end
end
I'm newish at RoR so any input is welcome. Thanks in advance!
EDIT
Here is what is returned from rails console when given Item.first.vendors
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 => []
SOLUTION EDIT I had some fundamental errors in my model associations that wouldn't allow me to utilize those relationships. I cleaned up those associations by getting rid of duplicate fields (in this case :item_id and :product_code) and the answer below worked perfectly.