So I have a model called cities and a model called stores. I would like to connect my stores and cities model so that I will be able to call on the store’s city if needed (e.g. @Store.city). How would I go about doing so?
I’m assuming that I need a has_many :cities tag in the store model and a belongs_to :store tag in the cities model. I get kind of lost past that point. Any help would be very much appreciated?
First warning is that. Unless intended to, it is unconventional to use plural for model name in RoR. So your
Storesshould beStore. Similarly, for city.I am guessing that you want to have a relationship where a city has_many stores. In this case, You would want a foreign key in your store signifying that the store belongs_to a city.
in your Store model, you want to add
in your city model, you want to add
Update
Make sure that in your your store table, you have a foregin key named
city_idAnswers
“What do I do with the foreign key?”
You only have to add it to the table. Rails will automatically make this connection for you. To be more precise. In your
storestable migration, make sure you have