好的,我在_form.html.erb
<div class "field">
<%= label_tag "What days of the week do you want to work with us? (maximum of three days)" %>
<span>What days of the week do you want to work with us? (maximum of three days)</span><br />
<%= check_box_tag 'days_of_week[]', "Monday" %> Monday
<%= check_box_tag 'days_of_week[]', "Tuesday" %> Tuesday
<%= check_box_tag 'days_of_week[]', "Wednesday" %> Wednesday
<%= check_box_tag 'days_of_week[]', "Thursday" %> Thursday
<%= check_box_tag 'days_of_week[]', "Friday" %> Friday
<%= check_box_tag 'days_of_week[]', "Saturday" %> Saturday
<%= check_box_tag 'days_of_week[]', "Sunday" %> Sunday
</div>
如何为其编写自定义验证以确保某人检查三个或更少?
这是一个让它复杂化的小背景..看下面的代码,请参阅@new_partnership?它不是它的一部分......它确实显示在参数中,但不在:new_partnership参数中。
只是想解释一下。
<%= form_for(@new_partnership) do |f| %>
<% if @new_partnership.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@new_partnership.errors.count, "error") %> prohibited this new_partnership from being saved:</h2>
<ul>
<% @new_partnership.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
如果我需要提供额外的信息,请告诉我。
编辑1
此外,在任何人建议jQuery等之前......有没有办法在ROR中验证这一点而不必诉诸它?
你知道,这样的事情:
validates :days_of_week, :presence => { :message => "Must check three or less" }
上述声明中的两个问题,一个是ROR说days_of_week是未定义的方法(显然因为它是自定义标记),其次,它实际上并不检查是否检查了3个或更少的复选框。
答案 0 :(得分:1)
您始终可以使用validates_each
:
validates_each :days_of_week do |record, attr, value|
record.errors.add attr, ' must have 3 or fewer checked.' if value.length > 3;
end
请注意,要使其工作,您的模型必须能够使用数组值属性,这可能需要专门的访问器。
你在问题的“背景”部分写的内容并不代表我能看到的任何内容。