开发者

Calling valid? on new records, but ignore validity of built associations

I have three tables: tasks, departments, and department_tasks. I need to call "valid?" on new task objects, but I want to ignore the validity of any "built" department_tasks. We are doing bulk uploads, and so we load everything or nothing.

As we loop through the Excel file we are reading in, we build the new "Task" according to the values in each row. With each row, there may be an associated department for the task; if there is, we "build" the associated department_task object like so:

new_task.department_tasks.build(:department_id => d.id)

At the end of the loop, we test the validity of the new "task" object by calling "valid?"

new_task.valid?

If the task is valid, it goes in the "good" pile; if it's bad, it goes on the "bad" pile.

The problem is, we haven't saved the task and therefore it has no :id. Without an id, the "built" department_task is invalid (:department_id and :task_id must both be present).

I need to know how I can call "valid?" or test validity of the "new_task" object without the validation cascading down to the "task_department" associated obje开发者_高级运维ct which cannot be valid before task is saved.


You can skip individual validations using :if or :unless

validates_presence_of :department_id,
  :unless => lambda { |record| record.new_record? }

If I understand correctly, you have something like this:

class Task < ActiveRecord::Base
  has_many :department_tasks
  has_many :departments, :through => :department_tasks
  validates_associated :department_tasks
end

class DepartmentTask < ActiveRecord::Base
  belongs_to :task
  belongs_to :department
  validates_presence_of :department_id, :task_id
end

When Task is new the associated validation in DepartmentTask fails because task_id is nil. Correct?

I don't see an easy way around this. The most obvious solution is to just remove the validates_presence_of for task_id. If the only way that you create DepartmentTasks is to build them through the Task model, the presence_of validation seems unnecessary, since Rails will always add the task_id when Task is saved.

Another option is to wrap it in a transaction, create the new task (so it has an ID), then build and validate DepartmentTask, and rollback if invalid.


You should assign an object to your AR queries to check it's validity, also use .new(:department_id => d.id)

myrecord = new_task.department_tasks.new(:department_id => d.id)
if myrecord.save!
 "good pile"
else
 "bad pile"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜