Spyros
Spyros

Reputation: 48626

Rails Triple Associations

Consider three models. A user, an inventory and an inventory items one.

A user belongs to inventory. An inventory has one user. An inventory has many inventory items and an inventory item belongs to inventory. ( i know that a user has one inventory should probably be better, but i was less knowledgeable of ruby when doing my associations ).

Now, i was wondering what is the best way of, say, checking whether a user has a certain item in his inventory.

What do you think ? Maybe you would also suggest that i change my associations ? I'm open to criticism :)

Upvotes: 0

Views: 274

Answers (1)

gregor
gregor

Reputation: 4833

I think you should use the :through => ... option of has_many. For example:

class User ...
  has_many :inventory_items, :through => :inventories 

  ...
end

Then you can use find on the inventory_items collection of the user.

user = User.first
item = user.inventory_items.find(...)

For more informations see the rails api doc of ActiveRecord::Associations::ClassMethods.

Upvotes: 1

Related Questions