2016-05-24 56 views
0

什麼是驗證用戶一個答案輸入的最佳方式,下面的驗證規則:Ruby on Rails的驗證爲選擇題測試

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" %> 

in controller:

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) 
+0

你想檢查問題是否回答正確或錯誤。或者你的要求是其他的 –

+0

不,只是驗證有兩個選擇選擇 – Boboss

+0

你想提交後,提交按鈕?或者你想顯示它像一個Flash消息?它不清楚你的上面的代碼。請詳細說明。 –

回答

0

不知道我完全理解的需求,但似乎像這樣的事情:

class Question... 
    validate :validate_answers 

    def validate_answers 
    unless answers.length == 2 
     errors.add(:answers, 'must have 2 selected') 
    end 
    end 
end 
+0

另外,您的複選框名稱需要與模型屬性匹配。 '

+0

對不起,我在代碼中有錯誤,它是' Boboss

+0

question.answers.inspect在控制器中的值是什麼? –