Carsten Gehling
Carsten Gehling

Reputation: 1248

Rails 3.2+ AR: Complex attributes in separate model

I currently have a model called Trip with some "from" and "to" attributes like this (simplified for the sake of the question):

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

I would very much like to refactor this into something like this:

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

What I am trying to achieve is to create a model that should serve as a "complex attribute". But I am not quite sure, how and where I should place my associations. Is the above correct? Or should the belongs_to be in Trip instead of Location?

Upvotes: 0

Views: 62

Answers (1)

alek
alek

Reputation: 331

I would do something like this:

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

Upvotes: 1

Related Questions