Rails: validate presence of parent_id in has_many association
Posted
by deb
on Stack Overflow
See other posts from Stack Overflow
or by deb
Published on 2010-05-18T17:01:50Z
Indexed on
2010/05/19
17:10 UTC
Read the original article
Hit count: 150
I have a projects resource that has many tasks. I want to ensure that every task has a project_id
by adding validates_presence_of :project_id
to the tasks model.
However, when creating a new project with tasks, the project_id won't be available until the record saves, therefore I can't use validates_presence_of :project_id
.
So my question is, how do I validate presence of project_id in the task model? I want to ensure every task has a parent.
...
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
accepts_nested_attributes_for :tasks, :allow_destroy => true
...
class Task < ActiveRecord::Base
belongs_to :project
validates_presence_of :project_id
© Stack Overflow or respective owner