2010-04-02 108 views
1

我覺得這可能非常簡單,但我只是沒有正確理解,所以我喜歡在我的應用中設置頁面,我希望每個設置都像一個關鍵值存儲區,例如:Rails一次編輯多條記錄

+-------------------+--------------------------------+ 
| setting   | value       | 
+-------------------+--------------------------------+ 
| twitter_username | something      | 
+-------------------+--------------------------------+ 
| facebook_url  | http://facebook.com/someguy | 
+-------------------+--------------------------------+ 

我的形式看起來是這樣的:

<% form_tag set_admin_settings_path, :method => :put do %> 
    <ol> 
    <% for setting in @settings %> 
    <li class="field"> 
     <label><%= setting.setting_name.humanize %></label> 
     <%= text_field_tag "[setting_value][]", setting.setting_value %> 
    </li> 
    <% end %> 
    <li class="submit"> 
     <%= submit_tag "Update settings" %> 
    </li> 
    </ol> 

<% end %> 

一切呈現罰款,但是當我嘗試保存的形式,沒有保存:(

回答

3

這是我認爲它應該看起來,我已經修改了你的表單。這也假定你沒有對設置對象進行任何驗證,對於設置類的多個實例,驗證和顯示錯誤將會很棘手,但它可以完成。我的例子不會顯示任何錯誤。

配置/ routes.rb中

map.namespace(:admin) do |admin| 
    admin.resources :settings, :collection => { :set => :put } 
    end 

應用程序/控制器/管理/ settings_controller.rb

def set 
    #this is what I think your action should do 
    params[:settings].each do |setting| 
    @setting = Setting.find(setting[:id]) 
    @setting.update_attributes(setting) 
    end 

    redirect_to admin_settings_path 
end 

應用/視圖/管理/設定/ index.html.erb

<% form_tag set_admin_settings_path, :method => :put do %> 
    <ol> 
    <% for setting in @settings %> 
    <li class="field"> 
     <label> 
     <%= setting.setting_name.humanize %> 
     </label> 
     <!-- settings[][field_name] will group the settings objects in params --> 
     <%= hidden_field_tag("setting_#{setting.id}_id", 
          setting.id, 
          :name => 'settings[][id]') %> 
     <%= text_field_tag("setting_#{setting.id}_setting_value", 
         setting.setting_value, 
         :name => 'settings[][setting_value]) %> 
    </li> 
    <% end %> 
    <li class="submit"> 
     <%= submit_tag "Update settings" %> 
    </li> 
    </ol> 

<% end %> 
+0

太棒了!我認爲最能幫助我瞭解什麼是循環'params [:settings] .each'這是票證的事情,再次感謝。 – 2010-04-02 06:05:51

0

我認爲你需要如社會您的設置名稱與它的價值,也許嘗試類似

<%= text_field_tag "[#{setting.setting_name}][]", setting.setting_value %>