Skip to content

Instantly share code, notes, and snippets.

@gpr
Last active August 29, 2018 11:47
Show Gist options
  • Save gpr/d26b70d4312722d9e0a7 to your computer and use it in GitHub Desktop.
Save gpr/d26b70d4312722d9e0a7 to your computer and use it in GitHub Desktop.
How to manage polymorphic associations with simple_form and JQuery
<!-- 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 %>
<!-- app/view/images/_imageable_select.html.erb -->
<%= options_for_select(['None'], 'None') %>
<%= options_from_collection_for_select(@imageables, 'id', 'name') %>
# app/view/images/imageable_types.js.erb
$("#imageable_id_select").html(
"<%= escape_javascript(render partial: 'imageable_select') %>"
);
# 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/controllers/images_controller.rb
def imageable_types
type = params[:type] ? params[:type] : 'DefaultModel'
@imageables = = type.empty? ? [] : type.constantize.all
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.
# config/routes.erb
resources :image do
get 'imageable_types', on: :collection
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment