Ruby on Rails:在模型上使用 form_for 并翻转表单值

发布于 2024-09-14 19:32:18 字数 431 浏览 4 评论 0原文

我有一个 form_for 表单,在其中,我使用了一个表单助手复选框。该模型有一个布尔值字段,但我希望能够以相反的方式在我的表单上显示它,因为我认为这更容易让用户理解。

有什么方法可以让 Rails 表单助手表现得就像模型的布尔字段被翻转一样吗?

示例:

<% form_for :user do |form| %>
  <%= form.check_box :privacy_disabled %>
<% end %>

在此示例中,用户模型有一个布尔字段privacy_disabled 。我想在表单中显示此信息,并在此处选中以启用隐私。

复选框辅助函数能够设置其选中和未选中的值,但反转这些值似乎无法使用预先保存的值正确填充复选框。

I've got a form_for form, and within it, I'm using a form helper check box. The model has a field that's a boolean value, but I'd like to be able to display it on my form in terms of its converse since I think that's easier for users to understand.

Is there any way for me to have a Rails form helper act as if the model's boolean field is flipped?

Example:

<% form_for :user do |form| %>
  <%= form.check_box :privacy_disabled %>
<% end %>

In this example, the User model has a boolean field privacy_disabled. I would like to display this in the form as check here to enable privacy.

The checkbox helper function has the ability to set its checked and unchecked values, but inverting these does not seem to properly populate the checkbox with the pre-saved value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

围归者 2024-09-21 19:32:18

这就是我最终解决这个问题的方法,我实际上已经接近第一次尝试了:

<%= form.check_box :privacy_disabled, 
                   {:checked => [email protected]_disabled}, 
                   0,
                   1 %>

因此复选框返回的值被翻转,并且是否开始检查也是手动翻转的。

This is how I ended up solving this issue, I was actually close with my first attempt:

<%= form.check_box :privacy_disabled, 
                   {:checked => [email protected]_disabled}, 
                   0,
                   1 %>

So the values returned by the checkbox are flipped, and whether it starts out checked is manually flipped as well.

何以畏孤独 2024-09-21 19:32:18

这不是最优雅的解决方案,但您可以执行如下操作:

  1. 将这些方法添加到您的用户模型中:

    defprivacy_enabled=(val)
      self.privacy_disabled = val == "0"
    结尾
    def 隐私启用
      !privacy_disabled
    结尾
    
  2. 将表单更改为:

    <%= form.check_box :privacy_enabled %>
    

再次,虽然不优雅,但有效。

Not the most elegant solution, but you could do something like the following:

  1. Add these methods to your user model:

    def privacy_enabled=(val)
      self.privacy_disabled = val == "0"
    end
    def privacy_enabled
      !privacy_disabled
    end
    
  2. Change the form to:

    <%= form.check_box :privacy_enabled %>
    

Again, not elegant, but it works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文