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

时间:2013-07-31 07:08:29

标签: ruby-on-rails activerecord rails-activerecord

我目前有一个名为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?

1 个答案:

答案 0 :(得分: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