0

我目前有一个名为 Trip 的模型,其中包含一些像这样的“from”和“to”属性(为了问题而简化):

class Trip < ActiveRecord::Base
  attr_accessible :from_street, :from_zip, :from_country, :to_street, :to_zip, :to_country
  ...
end

我非常想将其重构为如下内容:

class Trip < ActiveRecord::Base
  has_one :from_location
  has_one :to_location
  ...
end

class Location < ActiveRecord::Base
  belongs_to :trip

  attr_accessible :street, :zip, :country
  ...
end

我想要实现的是创建一个应该作为“复杂属性”的模型。但我不太确定,我应该如何以及在哪里放置我的关联。以上是正确的吗?或者,belongs_to 应该在 Trip 而不是 Location 中?

4

1 回答 1

1

我会做这样的事情:

class Trip < ActiveRecord::Base
  belongs_to :from_location, class_name: Location.name, foreign_key: 'from_location_id'
  belongs_to :to_location, class_name: Location.name, foreign_key: 'to_location_id'
  ...
end
于 2013-07-31T07:32:23.743 回答