验证用户输入的答案的最佳方法是什么,验证规则如下:
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
目录:
<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
答案是问题表中的字符串
这是一个数组,他有 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)
不确定我是否完全理解要求,但似乎是这样的:
class Question...
validate :validate_answers
def validate_answers
unless answers.length == 2
errors.add(:answers, 'must have 2 selected')
end
end
end