settheline
settheline

Reputation: 3383

Accessing rails attributes through deep associations

Here are my relevant models:

class ListItem < ActiveRecord::Base
    belongs_to  :inventory_item
    belongs_to  :shopping_list
    belongs_to  :item
end

class ShoppingList < ActiveRecord::Base
    has_many :list_items
    belongs_to  :user, :foreign_key => :user_id
end

class InventoryItem < ActiveRecord::Base

    belongs_to  :item, :foreign_key => :item_id
    belongs_to  :vendor
    has_many    :list_items
end

I'm trying to access attributes of InventoryItem in my view. Here's what I currently have in my ShoppingListController.

def show
  @list_items = ShoppingList.find(params[:id]).list_items
end

Can I do something like @inventory_items = @list_items.inventory_items? That code and variants of it that I've tried haven't worked. What am i missing here? Any tips for accessing attributes through multiple models like this? Thanks in advance!

Upvotes: 0

Views: 58

Answers (1)

steakchaser
steakchaser

Reputation: 5249

The most straight forward approach would be to use has_many through on the ShoppingList class:

has_many :inventory_items, through: :list_items

Upvotes: 1

Related Questions