Rails 复选框和序列化数据
我试图找出让复选框正确显示其当前状态的最佳方法。这就是我在表单中的
<%= 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
我的问题是,无论我尝试什么,我都无法让复选框反映哈希值的现有状态。 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 %>
丑陋但工作,仍然希望我错过了一些非常明显的东西
I'm trying to figure out whats the best way to get checkboxes to properly show their current state. This is what I have in my form
<%= 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 is a serialized hash on my user model
class User < ActiveRecord::Base
serialize :notification_preferences, Hash
My issue that is no matter what I try, I can not get the check boxes to reflect the existing state of the hash values. IE, if the hash already contains :notify_on_friend_post => 1, then the check box for that value should be checked.
The form posts the data fine, and I'm able to update my model as well.
Update
using check_box_tag I can get this to work
<%= 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 %>
ugly but working, still hoping I'm missing something very obvious
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了这个问题并以更简单的方式解决了它。
通过这种方式,您可以发挥 check_box 的魔力,并且不需要隐藏字段,因为 Rails 将为您提供一个隐藏字段。仍然不确定为什么需要一个“检查”字段,但如果没有它似乎就无法工作。
I ran into this problem and solved it in a simpler way.
In this way you let the magic of check_box to the work and don't need to have a hidden_field because Rails will provide one for you. Still unsure why you need a "checked" field, but it seemed to not work without one.
尝试这样的事情:
Try something like this: