I can create a statistic
for a given person
like this:
@person = Person.find(person.id)
@statistic = @person.statistics.build(:value => @value, :updated => @updated)
There's a one-to-many
(has_many
/belongs_to
) relationship between person
and statistic
.
The above works fine.
However, I also want the statistic
to belong to a race
too (race as in running/driving race) i.e. I have changed my statistic
model to have two belongs_to
s:
belongs_to :person # just had this before
belongs_to :race # this is new
Is the above correct or do I need to use a through
in my models somehow? If so, how?
How do I alter my controller code for this change?
Many thanks.
If you want statistic
to belong to race
only, you don't need to use has_many :through
. All you need to do is to add the new reference when building a statistic
entry by either a new object:
@race = Race.new(....)
@person.statistics.build(value: @value, updated: @updated, race: @race)
or by foreign key (if the referenced race already exists)
@person.statistics.build(value: @value, updated: @updated, race_id: @race.id)