如果在rails中验证则添加

时间:2016-04-20 16:49:34

标签: ruby-on-rails ruby-on-rails-4 simple-form ruby-on-rails-5

我搜索解决方案需要多个响应选择(3), whitout" check_must_be_3"我没有问题。 如果我添加此解决方案,我会回滚。 这是我的想法,但似乎没有用!

model.rb:

validates :check, presence: true
validate :check_must_be_3

  private
    def checks_must_be_3
      if !check != 3
        errors[:base] << "You must select exactly 3 checks"
      end
    end

HTML:

<%= simple_form_for @answer do |f| %>
  <h3>Choose 3 answers</h3>
    <ul>
    <% (1..5).each do |x| %>
      <div class="checkbox">
        <label>
          <input type="checkbox" name="answer[check][]" id="optionsCheckbox<%= x %>" value="<%= x %>" />
          <%= x %>
        </label>
      </div>
    <% end %>
    <%= f.button :submit, "Submit", class: "btn btn-primary" %>
<% end %>

控制器:

private

def answer_params
    params.require(:answer).permit(check:[])
end

1 个答案:

答案 0 :(得分:2)

#try this
    private
    def checks_must_be_3
      unless check.count == 3
        errors.add(:base , "You must select exactly 3 checks")
      end
    end