在表单提交时触发Rails中的自定义验证

时间:2011-12-03 03:06:24

标签: ruby-on-rails validation

我有一个表单,其中数据被提交给模型猜测。

<%= form_for(@guess) do |f| %>

表单是一堆复选框,我想确保检查6个中的至少2个。

有人帮我完成了我在Guess模型中添加的自定义验证

validates_inclusion_of :check_box_count, :in => 2..2, :message => "Two checkboxes should be ticked"

...

private 


def check_box_count
  [secondanswer_chambersapp, secondanswer_drafting, secondanswer_letter,
  secondanswer_interview, secondanswer_solicitor, secondanswer_barrister
  ].select{|x| x }.count
end

但是,我不明白如何在从视图提交表单时触发此方法。这就是整个表格的样子。我在导轨指南中看了6.2,但对于我这个简单的新手大脑来说太麻烦...... http://guides.rubyonrails.org/active_record_validations_callbacks.html#performing-custom-validations

您能否建议我如何将表单提交与触发验证方法联系起来?

<%= form_for(@guess) do |f| %>
  <% if @guess.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@guess.errors.count, "error") %> prohibited this guess from being saved:</h2>

      <ul>
      <% @guess.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>


<div class="field">
    <%= f.label(:secondanswer_chambersapp, "Chambers app") %>
    <%= f.select:secondanswer_chambersapp, 1..6 %> </br>
    </div>

    <div class="field">
    <%= f.label(:secondanswer_drafting, "Drafting") %>
    <%= f.select :secondanswer_drafting, 1..6 %> </br>
    </div>

    <div class="field">
     <%= f.label(:secondanswer_interview, "Interview") %>
    <%= f.select :secondanswer_interview, 1..6 %> </br>
    </div>

    <div class="field">
    <%= f.label(:secondanswer_letter, "Client Letter") %>
    <%= f.select:secondanswer_letter, 1..6 %> </br>
    </div>

    <div class="field">
    <%= f.label(:secondanswer_barrister, "Barrister's exam") %>
    <%= f.select:secondanswer_barrister, 1..6 %> </br>
    </div>

    <div class="field">
    <%= f.label(:secondanswer_solicitor, "Solicitor's exam") %>
    <%= f.select:secondanswer_solicitor, 1..6 %> </br>
    </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

2 个答案:

答案 0 :(得分:0)

尝试保存记录时会发生模型验证。在您的控制器中,在表单提交后处理数据的方法应该在某个时刻调用@ guess.save。这是模型运行验证时的情况。最简单的逻辑如下:

def create
  @guess = Guess.new(params[:guess])
  if @guess.save # Model validations are run
    redirect_to guesses_url # Validations passed
  else
    render 'new' # Validations did not pass
  end
end

答案 1 :(得分:0)

您可以在模型中指定自定义validate方法,该方法在保存之前调用

validate :checkboxes_have_enough_checked

private
def checkboxes_have_enough_checked
  [:secondanswer_chambersapp, 
   :secondanswer_drafting, 
   :secondanswer_letter,
   :secondanswer_interview, 
   :secondanswer_solicitor, 
   :secondanswer_barrister
  ].each do |attr|
    errors.add(attr, "At least 2 need to be checked!") if self.send(attr).to_i < 2
  end
end

如果存在错误,模型将无法保存。有关详细信息,请参阅http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods