gpr
4/23/2015 - 2:34 PM

How to manage polymorphic associations with simple_form and JQuery

How to manage polymorphic associations with simple_form and JQuery

# config/routes.erb

  resources :image do
    get 'imageable_types', on: :collection
  end
# app/controllers/images_controller.rb

def imageable_types
  type = params[:type] ? params[:type] : 'DefaultModel'
  @imageables = = type.empty? ? [] : type.constantize.all
end
# app/assets/javascripts/images.js

jQuery(function() {
    $('#imageable_type_select').on('change', function () {
        var selected = $(this).find(':selected').val();
        var url = $(this).attr('data-url').replace('selected', selected)

        $.ajax({
            url: url,
            processData: false,
            contentType: false,
            dataType: 'script'
        });
        return false;
    });
});
# app/view/images/imageable_types.js.erb

$("#imageable_id_select").html(
    "<%= escape_javascript(render partial: 'imageable_select') %>"
);
<!-- app/view/images/_imageable_select.html.erb -->

<%= options_for_select(['None'], 'None') %>
<%= options_from_collection_for_select(@imageables, 'id', 'name') %>
<!-- app/view/images/_form.html.erb -->

<%= simple_form_for(@image) do |f| %>
    <%= f.error_notification %>

    <div class="form-inputs">
        <%= f.input :imageable_type, collection: @imageable_types,
                      :input_html => {id: 'imageable_type_select', 
                      'data-url' => imageable_types_images_path(type: 'selected')} %>
        <%= f.input :imageable_id, collection: [], input_html: {id: 'imageable_id_select' } %>              
    </div>

    <div class="form-actions">
      <%= f.button :submit %>
    </div>
<% end %>

Introduction

How to manage polymorphic associations with simple_form and JQuery?

This is a solution.

.
├── app
│   ├── assets
│   │   └── javascripts
│   │       └── images.js
│   ├── controllers
│   │   └── images_controller.rb
│   └── view
│       └── images
│           ├── _form.html.erb
│           ├── _imageable_select.html.erb
│           └── imageable_types.js.erb
└── config
    └── routes.rb

Hints

JQuery

jQuery(function() { ... }); is mandatory to make sure that the Javascript will work.

data-url is uses as a parameter for the Javascript function.

TODOs

  • Scope the method imageable_types to render only js request.