Validations with HABTM relationships

I have a couple questions regarding validation.

I have a table with a HABTM relationship to another table. The table
is “task” and it has HABTM “employee_types”. Is there any way to have
a validation to make sure when a task is created it is associated with
at least one “employee_type”? I could include code to make sure of
this in the controller method but I’m wondering there is a built rails
way, or a way to stick a validation method into the “task” model.

a “task” also has the following relationship defined:

has_many :work_area_tasks, :dependent => :destroy, :order => :position
has_many :work_areas, :through => :work_area_tasks

Again, I’d like to make sure at least one “work_area_task” is created
with each “task”.


Sterling A.
sterling [at] sterlinganderson.net
http://sterlinganderson.net/
608.239.8387

Sterling A. wrote:

I have a table with a HABTM relationship to another table. The table
is “task” and it has HABTM “employee_types”. Is there any way to have
a validation to make sure when a task is created it is associated with
at least one “employee_type”? I could include code to make sure of
this in the controller method but I’m wondering there is a built rails
way, or a way to stick a validation method into the “task” model.

Unless there is a good reason to stay with habtm, I’d say you should
shift to using a join model with has_many :through. Then you’ll have a
model class to put the validation in.

a “task” also has the following relationship defined:

has_many :work_area_tasks, :dependent => :destroy, :order => :position
has_many :work_areas, :through => :work_area_tasks

Again, I’d like to make sure at least one “work_area_task” is created
with each “task”.

You need to create/save the task before you can create a join model
record associating it to a work area, so you can’t use vanilla
validations. You’ll have to find another place in your workflow to
validate that. If you always create a task with an associated work_area,
you could make a Task class method that creates all the records required
together in a transaction and validates them as a set. You can also put
a before_destroy callback in the join model to check if it is the only
record with its task_id.


Josh S.
http://blog.hasmanythrough.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs