代码
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
我的调查控制器
def new
@survey = Survey.new
2.times {@survey.questions.build}
end
表格
<%= 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 %>
正如您在用户创建调查时所看到的那样,表单提供了两个问题,我希望用户在创建调查时至少提供一个问题。怎么能实现???
答案 0 :(得分:4)
您只需测试数组的长度,然后执行:
validates :questions, length: {minimum: 1, message: 'should have at least 1 question defined.'}
答案 1 :(得分:1)
其中一个选项是使用自定义验证:
validate :questions_count
private
# or something more explicit, like `at_least_one_question` (credits to @MrYoshiji)
def questions_count
errors.add(
:base,
'You can not save a survey without questions. Add at least one question'
) if questions.none?
end
基本上,每次创建或触摸&#34;时都会触发验证。 (更新)survey
对象,如果survey
不会至少有一个question
关联,则会失败。