Skip to content

Using a Model with Pre populated Data

richlewis14 edited this page Nov 12, 2012 · 4 revisions

The Association between models is slightly different when dealing with a model who's data is pre populated.

In this example we will take a recipe model and a country model. The country model already has all its data populated and will never change.

The Associations

When i first tried this I said that a recipe has_one country and the country belongs to the recipe....This is incorrect, the actual relationship is

Recipe

belongs_to :country

Country

has_many :recipes

The foreign Key will be placed in the recipes model ( country_id) in this case.The rule is that whichever model has the belongs_to it must have a foreign_key to the model it belongs to, so country_id is needed in this case as specified

Lessons learned from this implementation

The country model is not a nested resource You do not have to build this attribute as it is already there (see build for nested attributes)