对rails中数据模型规划的建议

时间:2014-01-20 01:06:51

标签: ruby-on-rails model-associations

我在Rails上很新,我正在设置一个基于用户的新应用程序。我的数据模型有点复杂,所以我试图弄清楚我必须与每个用户关联多少。这是一个通用的纲要:用户有一个项目清单。每个项目都有以下内容:

标题 日期 数量 价钱 状态[出售,出售,非出售] 位置

- 丁 -

如果用户有多个商品的副本/版本,这样每个位置可能有N个数字,有价格,有些数字会被售出,未售出等等。

我考虑过这样的模型设置:

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]

这是正确的关联概念吗?我是否必须将ItemSet与用户关联?我永远不会在他们与物品的关联之外展示他们......谢谢,我希望这是有道理的!

1 个答案:

答案 0 :(得分:1)

# 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
相关问题