2011-05-19 34 views
1

我想弄清楚什麼是最好的方式來讓複選框正確顯示其當前狀態。這是我在我的形式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 %> 

難看,但工作時,仍然希望我失去了一些東西很明顯

回答

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 %> 
+0

更接近,更新我的答案與我想出沿着那條道路前進 – Kelend 2011-05-26 17:22:32

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

這樣,你讓check_box到工作的法寶,並不需要有一個hidden_​​field因爲Rails會提供一個給你。仍然不確定爲什麼你需要一個「檢查」字段,但它似乎沒有一個工作。