2017-03-01 52 views
0

我想創建一個用戶註冊表單,必須接受一組條款和條件,但我不知道如何使用複選框的值來驗證它是否被點擊(服務器端)。Rails的form_for複選框驗證沒有記錄在數據庫中

我試過用這個http://guides.rubyonrails.org/active_record_validations.html#acceptance,但到目前爲止我還沒有取得任何成就。

我在我的User.rb和我的表格<%= f.check_box :terms_of_service,:value =>'0',:class =>"hidden", :id =>"t_and_c" %>中有validates :terms_of_service, acceptance: { accept: '1' },但是我可以不點擊它就提交表單。我究竟做錯了什麼?如果我必須發佈其他內容才能讓問題更容易理解,請告訴我。

回答

0

在您的表單中,當複選框單擊它時應該返回true。

在你的表單,你只需指定,如果複選框被選中與否:

<%= f.check_box :terms_of_service %> Accept Terms of Services 
check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") 

在你的控制器,你剛剛保存取之於形式返回:

#you whitelist the parameter together with all the other params you have 
def user_params 
    params.require(:user).permit(:terms_of_services) 
end 

#You create your user as usual 
def create 
    @user = User.new(user_params) 
end 

在你的遷移,我會爲:terms_of_services添加一個默認選項以使其更加明確。

class AddTermsOfServicesToUser < ActiveRecord::Migration 
    def change 
    add_column :users, :terms_of_services, :boolean, default: false 
    end 
end 

編輯

如果不建立在你的用戶模型中的列,你沒有辦法用在服務器端服務方面的工作。只有在不需要創建列的情況下,您纔可以在客戶端使用terms_of_servies。這是你如何能做到這一點:

沒有Rails的check_box幫助創建一個複選框(因爲它會要求你沒有,因爲你在數據庫中沒有列的對象)

<input type="checkbox" id="cbox1" value="accepted" onchange='enableSubmitTag(this)'> 
    <label for="cbox1">Accept Terms of Services</label> 

禁用提交按鈕默認爲

<%= f.submit "Create", class: "btn btn-primary", id: "submit_button", disabled: true%> 

當他們單擊服務條款複選框時,再次啓用提交按鈕。

function enableSubmitTag(element) { 
    if(element.checked){ 
    document.getElementById('submit_button').disabled = false; 
    } else { 
    document.getElementById('submit_button').disabled = true; 
    }; 
}; 

如果您在表中存儲:terms_of_services,則可以在服務器端驗證它。你可以使用所有的JavaScript。你只需要改變的複選框:

<%= f.check_box :terms_of_service, :onchange => 'enableSubmitTag(this)' %> Accept Terms of Services 
+0

你能格式化rails的答案嗎? –

+0

我更新了我的答案。我還會在模式中將:terms_of_services的默認值設置爲false。這樣用戶明確地必須將其更改爲true。 –

+0

我知道如何使用它,如果我把它當作列表放在我的表格中。我想檢查如何可以嘗試沒有。 –

0

型號應該有:

validates :terms_of_service, acceptance: true 

形式應該有:

<%= form_for :user, url: users_path do |f| %> 
    ... 
    <%= f.label :terms_of_service %><br> 
    <%= f.check_box :terms_of_service %> 
    ... 
<% end %> 

和Rails應該爲你做的一切。