JP Silvashy
JP Silvashy

Reputation: 48525

Rails editing multiple records at once

I feel like this might be really simple but I'm just not getting it right, so I have like a settings page in my app and I want each setting to be like a key value store, for example:

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

My form looks something like this:

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

Everything renders fine but when I try to save the form, nothing is saved :(

Upvotes: 1

Views: 456

Answers (2)

Patrick Klingemann
Patrick Klingemann

Reputation: 9014

This is how I think it should look, I've modified your form a bit. This also assumes you're not doing any validation on the setting objects, validation and displaying errors would be tricky with multiple instances of the Setting class in a single form, but it could be done. My example will not display any errors.

config/routes.rb

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

app/controllers/admin/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

app/views/admin/settings/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 %>

Upvotes: 3

Corey
Corey

Reputation: 2243

I think you need to associate your setting name with it's value, maybe try something like

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

Upvotes: 0

Related Questions