Code
class Survey < ApplicationRecord
has_many :questions, inverse_of: :survey, :dependent => :destroy
accepts_nested_attributes_for :questions
validates_associated :questions
end
class Question < ApplicationRecord
belongs_to :survey, inverse_of: :questions
validates_presence_of :survey
end
My Surveys Controller
def new
@survey = Survey.new
2.times {@survey.questions.build}
end
Form
<%= form_for @survey do |f|%>
<p>
<%= f.label :name%>
<%= f.text_field :name%>
</p>
<%= f.fields_for :questions do |builder|%>
<p>
<%= builder.text_area :content, rows: 3%>
</p>
<% end %>
<p><%= f.submit %></p>
<% end %>
As you can see when user creates a survey the form provides two questions, i want user to supply at least one question when creating the survey. How can it be achieve???
validates :questions, presence: truewould be sufficient. I don't know if the built-it rails validation actually test the presence (something likeself.questions.present?). If yes, then it should be finevalidates :questions, presence: truewould work. I would prefer the customvalidateexclusively because of more control over validation's logic