gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:53 25 4
gpt4 key购买 nike

代码

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

我的调查 Controller

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

如您所见,当用户创建调查时,表单会提供两个问题,我希望用户在创建调查时至少提供一个问题。怎么实现???

最佳答案

你可以只测试数组的长度,然后简单地做:

validates :questions, length: {minimum: 1, message: 'should have at least 1 question defined.'}

关于ruby-on-rails - 如何验证至少一个嵌套对象的存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com