添加 if 在 rails 中验证

Adding if validates in rails

我搜索一个解决方案,需要多个响应选项 (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
#try this
    private
    def checks_must_be_3
      unless check.count == 3
        errors.add(:base , "You must select exactly 3 checks")
      end
    end