Domanda

I'm pretty new at Rails and am setting up a new application that is user based. My data model is a bit complicated so I'm trying to figure out how much I have to associate with each user. Here's a generic rundown: a user has an inventory of items. Each item has the following:

Title Date Quantity Price Status [for sale, sold, not for sale] Location

-BUT-

It is possible that if the user has many copies/versions of an item so that each location may have N number, with a price, some number are sold, unsold, etc.

I've thought about having a model setup like this:

User
has_many :items
has_many :locations
has_many :itemSets # <--- DO I NEED THIS???

Item
belongs_to :user
has_many :item_sets
Title
Date
Quantity

ItemSet
belongs_to :item
has_one :location
belongs_to :user # <--- ???
Quantity
Price
Status [sold, for sale, not for sale]

Is this the right association concept? And do I have to associate ItemSets to users? I'll never be showing them outside of their association with an item... Thanks and I hope this makes sense!!

È stato utile?

Soluzione

# users table shouldn't require any foreign key columns
class User
  has_many :items
  has_many :item_sets, :through => :items
  has_many :locations, :through => :items
end

# items table should have 'user_id' column
# other attributes would be 'title', 'date'
# quantity should be retrieved through the item_sets - see quantity method
class Item
  belongs_to :user
  has_many :item_sets
  has_many :locations, :through => :item_sets

  def quantity
    item_sets.sum(:quantity)
  end
end

# item_sets table should have 'item_id', 'location_id' columns
# other attributes would be 'quantity', 'price', 'status'
class ItemSet
  belongs_to :item
  belongs_to :location

  # now to make the user available you can either do this:
  delegate :user, :to => :item
  # or this:
  has_one :user, :through => :item
end

# locations table should not require any foreign key columns
class Location
  has_many :item_sets
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top