Search code examples
ruby-on-railsactiverecordactiveadminformtastic

ActiveAdmin edit multiple models in the same custom form loaded from a partial


I have this scenario that I can't figure out how to make it work. I have a Setting model. The model has two fields, key and value. So for each new setting I need to add to my rails app I just create a new Setting model with the key and the value I want.

I'm using ActiveAdmin, and I need to create a form that let's me edit all the keys at the same time, that means edit all the models from settings (Setting.all) at the same time from the very same form.

So I've been able to render a custom partial when trying to edit, but the problem is I can't find documentation or any info related on how to edit all at the same time. Also I've been reading about formtastic, and no luck :(

Any clue?!?!


Solution

  • My guess is that you'd be better off writing a custom view, and adding custom actions.

    Here is what it would look like:

    app/admin/settings.rb

    ActiveAdmin.register Setting do
      ...
      # Add a link on the index page to go the edit all page
      action_item :only => :index do
        link_to 'Edit Settings', :action => :edit_settings
      end
    
      member_action :edit_settings do
        @settings = Setting.all
      end
    
      member_action :update_settings, :method => 'post' do
        params[:settings].each do |setting_params|
          setting = Setting.find(settings_params[:id]
          setting.key = settings_params[:key]
          setting.value = settings_params[:value]
          setting.save
        end
      end
    
      ...
    end
    

    app/views/admin/edit_settings

    <form action="/admin/update_settings" method="POST">
        <% @settings.each do |setting| %>
            <div>
                <input id="setting_id_<%= "#{setting.id}" %>" name="settings[][id]" value="<%= setting.key %>" type="hidden" />
                <div>
                    <label for="setting_key_<%= "#{setting.id}" %>">Setting key</label>
                    <input id="setting_key_<%= "#{setting.id}" %>" name="settings[][key]" value="<%= setting.key %>" type="text" />
                </div>
                <div>
                    <label for="setting_value_<%= "#{setting.id}" %>">Setting value</label>
                    <input id="setting_value_<%= "#{setting.id}" %>" name="settings[][value]" value="<%= setting.value %>" type="text" />
                </div>
            </div>
        <% end %>
        <input type="submit" value="Submit" />
    </form>
    

    Note that there might be a way to write this form using formtastic, though I find it simpler sometimes to write some basic html.