【问题标题】:Ruby on Rails validate presence of checkboxesRuby on Rails 验证复选框的存在
【发布时间】:2014-10-27 03:30:45
【问题描述】:

下面的模型我有以下表格:

    = simple_form_for @mem, :url => signup_path, :html => {:id => 'signup_form'}, :method => :post do |f|

        = f.input :interest, label: "I would like to learn more about:", collection: [ ['Interest 1', 'Interest 1' ], ['Interest 2', 'Interest 2']], :as => :check_boxes
        %br
        = f.input :full_name, :as => :string, required: true
        = f.input :email, :as => :string, required: true
        = f.input :telephone, :as => :string, required: true

        = f.submit "Submit"

型号:

class User
    include ActiveModel::Validations
    include ActiveModel::Conversion
    extend ActiveModel::Naming
    attr_accessor :full_name, :email, :telephone, :interest
    validates :interest, presence: { :message => "Please select your interest."}

我能够成功验证表单中的其他 3 个字段,但是我无法验证复选框字段 :interest 的存在。我想确保用户选择其中一个或两个选项。感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 haml


    【解决方案1】:

    你可以试试

    接受:正确

    在你的模型中。

    validates :interest, acceptance: true
    

    【讨论】:

    • 我认为这最初是可行的,因为当两个选项都留空时它会引发错误,但在选择其中一个或两个选项时我似乎无法验证它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多