在您的表單中,當複選框單擊它時應該返回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
你能格式化rails的答案嗎? –
我更新了我的答案。我還會在模式中將:terms_of_services的默認值設置爲false。這樣用戶明確地必須將其更改爲true。 –
我知道如何使用它,如果我把它當作列表放在我的表格中。我想檢查如何可以嘗試沒有。 –