如何验证至少一个嵌套对象的存在?

时间:2016-10-13 20:29:32

标签: ruby-on-rails ruby

代码

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 %>

正如您在用户创建调查时所看到的那样,表单提供了两个问题,我希望用户在创建调查时至少提供一个问题。怎么能实现???

2 个答案:

答案 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关联,则会失败。