Rails associations clarification
I have a basic inventory tracking system. Each User can create an item with an optional location so that:
class User < ActiveRecord::Base
...
has_many :items, :dependent => :destroy
has_many :locations, :dependent => :destroy
end
class开发者_如何学JAVA Item < ActiveRecord::Base
...
validates :user_id, :presence => true
belongs_to :user
has_one :location
end
class Location < ActiveRecord::Base
...
validates :user_id, :presence => true
belongs_to :user
has_many :items
end
I can't quite get my head around who belongs to who! I know that each item and location must belong to the User. I also want an association so that each item can have one location, but I don't know if it has to be through the User. Am I making sense?
I am having difficulty with my inventory item form where it isn't recognizing any locations and so I think I must have my models set up incorrectly.
Unless you're doing something where a user would have a location directly, this should be what you need.
class User < ActiveRecord::Base
has_many :items
has_many :locations, :through => :items
end
class Item < ActiveRecord::Base
belongs_to :user
belongs_to :location
end
class Location < ActiveRecord::Base
has_many :items
has_one :user, :through => :items # Only if you want `Location#user` methods
end
An item belongs_to
a user — that much we can agree on. An item also belongs_to
a location because, simply, we want the foreign key on the item model so that a multitude of items can be associated with the same location.
You probably don't want locations to be user-specific, so no complementary has_one :user
association on the location model.
Think of belongs_to as a way to specify a foreign key.
Other than that, think in natural language.
A user has an inventory
An inventory has items
An item has a location
A user has items through inventory
A user has locations through items(possibly, if you want that)
Associations are just a way to get facilities like user.inventory.items or user.locations :)
EDIT
A user-location is a many to many association. That means, that you need a third user_locations table that belongs to user and location. That is unless a location belongs to only one user. Otherwise, if two users and more can have the same location, you need a through user_locations model.
精彩评论