So I’m creating a plugin for Ruby on Rails to make implemented addresses including country, state, city, and zip_code for countries that can follow that paradigm a lot easier but that’s beside the point expect for how the address model is associated.
So starting with my address model.
class Address < ActiveRecord::Base
has_one :country
has_one :state
has_one :city
has_one :zip_code
end
What’s the difference between saying belongs_to and has_one
Seems to be the same thing because both only require one model to declare ownership and foreign_key
And it also seems that both are logical to say.
an address belongs to an account and an account has one address
Is this only semantics or is there are real difference
From ActiveRecord association’s perspective, any model with
belongs_todeclaration has the foreign key and any model withhas_onedeclaration has the primary key.If we go by the current state of your model then you have to ensure tables such as
countries,sates,cities, andzip_codeshave a column calledaddress_id. Presumably that’s not what you want.So you have to change your
Addressmodel as follows:Which also means you have to ensure
addressestable has the following columns:country_id,state_id,city_idandzip_code_id( I am assuming this is your current table structure).Edit [I extended my answer to address the questions raised in the comments section.]
In your example you should use
has_manyassociation ratherhas_oneassociation.You can make calls such as:
I have used has_one association in following scenarios.
1) User with a profile
2) Merchant account with a store