Validations for a has_many/belongs_to relationship
Posted
by Craig Walker
on Stack Overflow
See other posts from Stack Overflow
or by Craig Walker
Published on 2010-05-25T03:57:51Z
Indexed on
2010/05/25
4:01 UTC
Read the original article
Hit count: 268
I have a Recipe model which has_many Ingredients (which in turn belongs_to Recipe). I want Ingredient to be existent dependent on Recipe; an Ingredient should never exist without a Recipe.
I'm trying to enforce the presence of a valid Recipe ID in the Ingredient. I've been doing this with a validates :recipe, :presence => true
(Rails 3) statement in Ingredient. This works fine if I save the Recipe before adding an Ingredient to it's ingredients
collection. However, if I don't have explicit control over the saving (such as when I'm creating a Recipe and its Ingredients from a nested form) then I get an error:
Ingredients recipe can't be blank
I can get around this simply by dropping the presence validation on Ingredient.recipe. However, I don't particularly like this, as it means I'm working without a safety net.
What is the best way to enforce existence-dependence in Rails?
Things I'm considering (please comment on the wisdom of each):
- Adding a not-null constraint on the ingredients.recipe_id database column, and letting the database do the checking for me.
- A custom validation that somehow checks whether the Ingredient is in an unsaved recipe's ingredient collection (and thus can't have a recipe_id but is still considered valid).
© Stack Overflow or respective owner