简体   繁体   English

Rails 4 - 复选框和布尔字段

[英]Rails 4 - Checkbox and Boolean Field

I have looked at loads of different articles on the web (some on here) about this issue but there are so many different suggestions, lots of which are outdated, that it has led me to ask here today...我在网上查看了很多关于这个问题的不同文章(一些在这里),但是有很多不同的建议,其中很多已经过时了,这让我今天在这里问......

I have a field in my Users table called admin?我的用户表中有一个名为 admin 的字段? which is a :boolean data type.这是一种 :boolean 数据类型。 I also have a checkbox in the form in my view called admin?我的视图中的表单中还有一个名为 admin 的复选框? - I would like to be able to create TRUE and FALSE accordingly in the table record when the form is submitted. - 我希望能够在提交表单时在表记录中相应地创建 TRUE 和 FALSE。

Part of my view code is:我的部分视图代码是:

Admin User&#63; <%= f.check_box :admin? %>

Also I have permitted this in my post_params - is this a necessary step?我也在我的 post_params 中允许这样做 - 这是必要的步骤吗?

params.require(:staff).permit(:name, :email, :password, :password_confirmation, :admin?)

When I submit the form at the moment, the admin?当我现在提交表单时,管理员? field is unaffected.场不受影响。 Any advice would be much appreciated.任何建议将不胜感激。

No need to name it ":admin?"无需将其命名为“:admin?”

Just use this in your form:只需在您的表单中使用它:

Admin User&#63; <%= f.check_box :admin %>

And the permitted params like this:和允许的参数是这样的:

params.require(:staff).permit(:name, :email, :password, :password_confirmation, :admin)

That should work.那应该工作。

For anyone that has a form that isn't part of an object.对于任何拥有不属于对象的形式的人。

I found using checkbox syntax like:我发现使用复选框语法,如:

= check_box 'do_this', '', {}, 'true', 'false'

Then in the controller side:然后在控制器端:

ActiveRecord::ConnectionAdapters::Column.value_to_boolean(params[:do_this])

Will give you the correct boolean value of do_this .会给你正确的do_this布尔值。

Examples:例子:

[1] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("true")
=> true
[2] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("false")
=> false
[3] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("1")
=> true
[4] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("0")
=> false

Edit: The above is deprecated, use:编辑:以上已弃用,请使用:

ActiveRecord::Type::Boolean.new.type_cast_from_database(value)

It gives the same results as the examples above.它给出了与上述示例相同的结果。

Rails 5导轨 5

The above options don't work in Rails 5. Instead, use the following:上述选项在 Rails 5 中不起作用。相反,请使用以下内容:

ActiveRecord::Type::Boolean.new.cast(value)

It's possible you have not allowed your controller to accept the admin field through params.您可能没有允许您的控制器通过 params 接受 admin 字段。 In other words, an issue of strong parameters.换句话说,强参数的问题。 Ensure that :admin is permitted in your model_params.确保 :admin 在您的 model_params 中是允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM