settawut
settawut

Reputation: 23

Is it a good idea to use has_one nested attributes in rails?

Let's say if I have 3 models; Hotel, Resort and restaurant. Each model have similar attributes; title, description, facilities ...and so on...

If I want every models have one location with attributes; Country, Province, City, address, Latitude and Longitude.

Should I create location model and using has_one nested attributes or should I include location's attributes to those model? Which one is more preferable or better approach?

Upvotes: 1

Views: 109

Answers (1)

Deepesh
Deepesh

Reputation: 6398

I think you need to use polymorphic association as you need on model to belong to more than one model. You can use it like this:

Edit: Changing the belongs_to :address to belongs_to :locatable as @vee corrected it.

class Location < ActiveRecord::Base
  belongs_to :locatable, polymorphic: true
end

class Hotel < ActiveRecord::Base
  has_one :location, as: :locatable    
end
class Resort < ActiveRecord::Base
  has_one :location, as: :locatable    
end
class Restaurant < ActiveRecord::Base
  has_one :location, as: :locatable    
end

More Details: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Hope this helps.

Upvotes: 1

Related Questions