Ruby on Rails: one-to-one mapping. Just semantics or really a different structure
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
Seem开发者_JS百科s 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_to
declaration has the foreign key and any model with has_one
declaration 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
, and zip_codes
have a column called address_id
. Presumably that's not what you want.
So you have to change your Address
model as follows:
class Address < ActiveRecord::Base
belongs_to :country
belongs_to :state
belongs_to :city
belongs_to :zip_code
end
Which also means you have to ensure addresses
table has the following columns: country_id
, state_id
, city_id
and zip_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_many
association rather has_one
association.
class Country
has_many :addresses
end
class State
has_many :addresses
end
class City
has_many :addresses
end
class ZipCode
has_many :addresses
end
You can make calls such as:
country.addresses
state.addresses
city.addresses
zip_code.addresses
I have used has_one association in following scenarios.
1) User with a profile
User has one Profile
Profile belongs to User
2) Merchant account with a store
Merchant has one Store
Store belongs to Merchant
精彩评论