Rails 3.2+AR:独立模型中的复杂属性



我目前有一个名为Trip的模型,它有一些"from"one_answers"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中?

我会这样做:

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

最新更新