Rails协会澄清

时间:2011-03-22 02:25:55

标签: ruby-on-rails-3 associations

我有一个基本的库存跟踪系统。每个用户都可以使用可选的位置创建,以便:

class User < ActiveRecord::Base
  ...
  has_many :items, :dependent => :destroy
  has_many :locations, :dependent => :destroy
end

class 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

我无法理解属于谁的人!我知道每个项目和位置必须属于用户。我还想要一个关联,以便每个项目可以有一个位置,但我不知道它是否必须通过用户。我有道理吗?

我的库存物品表格有问题,因为它没有识别任何位置,所以我认为我的模型设置不正确。

2 个答案:

答案 0 :(得分:0)

将belongs_to视为指定外键的一种方式。

除此之外,用自然语言思考。

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)

关联只是获取user.inventory.items或user.locations等设施的一种方式:)

修改

用户位置是多对多关联。这意味着,您需要属于用户和位置的第三个user_locations表。这是除非一个位置只属于一个用户。否则,如果两个用户和更多用户可以拥有相同的位置,则需要通过user_locations模型。

答案 1 :(得分:0)

除非您正在做某个用户直接拥有位置的事情,否则这应该是您所需要的。

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

项目belongs_to用户 - 我们可以达成共识。一个项目belongs_to也是一个位置,因为我们只需要项目模型上的外键,以便多个项目可以与同一位置相关联。

您可能不希望位置是特定于用户的,因此位置模型上没有互补的has_one :user关联。