I have a small app that allows users to upload recipes and save favourite recipes. I have a separate model called country that has all the countries of the world within it which then allows users to select one from a dropdown.
Initially I had the association as
recipe
has_one :country
country
belongs_to :recipe
After some research the correct association is
recipe
belongs_to :country
country
belongs_to :recipe
The foreign key country_id going within the recipe model.
I’m going to do some more reading but was wondering if someone could explain as to why it is this association and not the first one
I guest you want to build association like this:
If so, you should define association is:
country:
recipe:
And i think your second association is also incorrect.
When you define
belongs_to :countryin Recipe model, it means your Recipe table must have a column calledcountry_id. It is a foreign key to Country model.In the first define association, the
Countrymodel will have a column calledrecipe_id, so, every country just has only one recipe, that’s not what you want, right? Why it’s not work? Because with one country you have only one record, so one country can have only one recipe, accessed throughrecipe_id.With first association, your association is One-to-One (One Country has one Recipe), while you actually want your association is One-to-Many ( One Country has Many Recipe). So it’s reason why first association not works (second too).
The main thing you need to remember here is, what model you put a
belongs_toassociation, that model will have a column called'association name'_id. The different between usinghas_oneandbelongs_toonly is where you put foreign key and the meaning of association. Check here to clearer.