【问题标题】:Rails checkboxes and serialized dataRails 复选框和序列化数据
【发布时间】:2011-08-29 03:07:28
【问题描述】:

我正在尝试找出让复选框正确显示其当前状态的最佳方法。这就是我的表单

<%= 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 %>

丑陋但工作,仍然希望我错过了一些非常明显的东西

【问题讨论】:

    标签: ruby-on-rails ruby forms serialization checkbox


    【解决方案1】:

    试试这样的:

     <%= form_for @user, :url => user_notification_preferences_path(@user), :method => :put do |f| %>
    
      <%= check_box_tag "user[notification_preferences][]", :notify_on_friend_post, @user.notification_preferences.try(notify_on_friend_post) %>
    
     <%= f.submit %>
    <% end %>
    

    【讨论】:

    • 更近一点,用我在这条路上的想法更新了我的答案
    【解决方案2】:

    我遇到了这个问题,用更简单的方法解决了。

    <%= 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 %>
    

    通过这种方式,您可以让复选框的魔力发挥作用,并且不需要隐藏字段,因为 Rails 会为您提供一个。仍然不确定为什么需要“已检查”字段,但如果没有它似乎就无法工作。

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 2015-08-29
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多