ネストされたモデルフォームについては、この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つのモデルすべてでネストされたフォームを作成するために使用されます。
問題は次のとおりです。新しいアンケートを作成し、アンケートにタイトルを付け、質問の内容を空白のままにして、回答を追加し、[送信]をクリックします。
調査が作成されます。ラムダのため、空白の質問フィールドと空白でない回答フィールドは破棄されます。
回答は存在するが質問は存在しない場合に検証をキャッチして、ユーザーが回答を削除するか質問を提供できるようにするにはどうすればよいですか?