Ruby on Rails验证多项选择测试

时间:2016-05-24 14:24:29

标签: ruby-on-rails ruby validation

验证用户的答案输入的最佳方法是什么,验证规则如下:

Examples of formats allowed 1, 2, 3, 4...to 12 

The value is 2 answers for 12 choices

模型:

class Questions < ApplicationRecord

  belongs_to :user

  validates :user, presence: true
  validates :answers, presence: true
end

HTML:

<h3>question</h3>
<% (1..12).each do |x| %>
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-danger btn-circle">
    <input type="checkbox" name="question[answer][]" id="optionsCheckbox<%= x %>" value="<%= x %>" />
    <%= x %>
  </label>
</div>
<% end %>
</ul>
<%= f.button :submit, "submit", class: "btn btn-success" %>
控制器中的

class QuestionsController < ApplicationController
skip_before_action :authenticate_user!, only: [ :new ]
before_action :find_question, only: [:show, :edit, :update, :destroy]

def create
    @question = Question.new(ticket_params)
    @question.user = current_user
    if @question.save
        redirect_to new_charge_path
    else
        render :new, alert: "Oops, something went wrong..."
    end
  end

    def question_params
    params.require(:question).permit(answer: [])
  end

  def find_question
    @question = Question.find(params[:id])
  end
end

answer是问题表中的一个字符串

这是一个数组,他有12个选择和2个可能的响应。就像一个多项选择测验..我只想定义可能的选择数量(2个选择)

这是我在控制台中的提交回复:

Started POST "/questions" for 127.0.0.1 at 2016-05-24 18:26:08 +0200
 Processing by QuestionsController#create as HTML
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"mAoBIf9jqDoungeeFKe6KitIf0ahAxhi6rVODmz6v1xGExYeVAVL8qXBfJj37KTpIkBBZJV2F1MRuBJKA==", "question"=>{"answer"=>["2", "8"], "commit"=>"Submit"}
 User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."id" ASC LIMIT 2  [["id", 6], ["LIMIT", 1]]
 (0.2ms)  BEGIN
 SQL (27.0ms)  INSERT INTO "questions" ("answer", "created_at", "updated_at", "user_id") VALUES (1, 2 ) RETURNING "id"  [["answer", "[\"2\", \"8\"]"], ["created_at", 2016-05-24 16:26:08 UTC], ["updated_at", 2016-05-24 16:26:08 UTC], ["user_id", 6]]
 (23.5ms)  COMMIT
Redirected to http://localhost:3000/charge/new
Completed 302 Found in 112ms (ActiveRecord: 51.3ms)

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解这个要求,但似乎是这样的:

class Question...
  validate :validate_answers

  def validate_answers
    unless answers.length == 2
      errors.add(:answers, 'must have 2 selected')
    end
  end
end
相关问题