我正在尝试找出让复选框正确显示其当前状态的最佳方法。这是我的表单中的内容
<%= form_for @user, :url => user_notification_preferences_path(@user), :method => :put do |f| %>
<%= f.fields_for :notification_preferences, @user.notification_preferences do |p| %>
<%= p.check_box :notify_on_friend_post %>
<%= p.check_box :notify_on_friend_post %>
<%= p.check_box :notify_on_friend_request %>
<%= p.check_box :notify_on_friend_comment %>
<% end %>
<%= f.submit %>
<% end %>
notification_preferences 是我的用户模型上的序列化哈希
class User < ActiveRecord::Base
serialize :notification_preferences, Hash
我的问题是无论我尝试什么,我都无法获得反射(reflect)哈希值现有状态的复选框。 IE,如果散列已经包含:notify_on_friend_post => 1,那么应该选中该值的复选框。
表单可以很好地发布数据,我也可以更新我的模型。
更新
使用 check_box_tag 我可以让它工作
<%= p.hidden_field :notify_on_friend_post, :value => "0" %>
<%= check_box_tag "user[notification_preferences][notify_on_friend_post]", "1", @user.notification_preferences[:notify_on_friend_post] == "1" ? true : false %>
丑陋但有效,仍然希望我遗漏了一些非常明显的东西
最佳答案
我遇到了这个问题,并以更简单的方式解决了它。
<%= form_for @user do |f| %>
<%= f.fields_for :notifications, @user.notifications do |n| %>
<%= n.check_box :new_task, checked: @user.notifications[:new_task] == "1" %>
<% end %>
<%= f.submit %>
<% end %>
通过这种方式,您可以发挥 check_box 的魔力,并且不需要 hidden_field,因为 Rails 会为您提供一个。仍然不确定为什么您需要一个“选中”字段,但没有它似乎无法工作。
关于ruby-on-rails - Rails 复选框和序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063302/