[英]How to validate files for multiple extension name checking in ruby or ruby on rails
[英]Ruby on Rails validate for multiple choice test
驗證用戶答案輸入的最佳方法是什么,驗證規則如下:
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
答案是問題表中的字符串
這是一個數組,他有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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.