What is the best way to set up a relationship between two tables where
table-1 has a one-to-one relationship with table-2 but table-2 has a
one-to-many relationship with table-1?
For example, suppose there is an events application (seminars, forums,
conferences, etc). Each event has only one address but since many
events can occur at the same location throughout the year, a given
address can belong to many events.
class Event < ActiveRecord::Base
belongs_to :address
end
class Address < ActiveRecord::Base
has_many :events
end
Don't let the seemingly backward "belongs_to :address" fool you. The 'belongs_to' association is on the model that contains the foreign key (address_id in this example) even though you say "Each event has only one address..." -- the "has ... one" is misleading in this case.
Don't let the seemingly backward "belongs_to :address" fool you. The
'belongs_to' association is on the model that contains the foreign key
(address_id in this example) even though you say "Each event has only
one address..." -- the "has ... one" is misleading in this case.