遵循此 RailsCast嵌套模型表单:
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
和
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
和
class Answer < ActiveRecord::Base
belongs_to :question
validates_presence_of :content
end
这些用于创建包含所有 3 个模型的嵌套表单。
问题是:我可以创建一个新调查,给调查命名,将问题内容留空,添加答案并单击提交。
调查已创建。由于 lambda,空白问题字段以及非空白答案字段被丢弃。
当存在答案但不是问题时,我可以做些什么来使验证捕获,从而允许用户删除答案或提供问题?