Chiperific
Chiperific

Reputation: 4686

Rails 3 ':reject_if => lambda' prevents validation?

Following this RailsCast for nested model forms:

class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

and

class Question < ActiveRecord::Base
  belongs_to :survey
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
  validates_presence_of :content
end

and

class Answer < ActiveRecord::Base
  belongs_to :question
  validates_presence_of :content
end

These are used to create a nested form with all 3 models.

Here's the issue: I can create a new survey, give the survey a title, leave the question content blank, add an answer and click submit.

The survey gets created. Because of the lambda, the blank question field is discarded as well as the not-blank answer field.

What can I do to make the validation catch when an answer is present but not a question, allowing the user to either delete the answer or provide a question?

Upvotes: 0

Views: 2459

Answers (1)

250R
250R

Reputation: 37151

One way is to remove the :reject_if when specifying the nested attribute.

Or if you need more flexibility, you can update the lambda to do more things, for example: to reject if both question and answer are empty.

Also look at the revised source code in github, which is helpful

Upvotes: 1

Related Questions