Rails一次编辑多个记录

时间:2010-04-02 03:57:59

标签: ruby-on-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 %>

一切都很好,但是当我尝试保存表单时,没有保存任何内容:(

2 个答案:

答案 0 :(得分:3)

这就是我认为它应该看起来的样子,我已经修改过你的表格了。这也假设您没有对设置对象进行任何验证,验证和显示错误在单个表单中使用Setting类的多个实例会很棘手,但是可以完成。我的示例不会显示任何错误。

配置/ 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 %>

答案 1 :(得分:0)

我认为您需要将设置名称与其值相关联,也可以尝试类似

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