Augusto Carmo
Augusto Carmo

Reputation: 4964

Rails Dynamic Form - call controller with the SimpleForm params to update the page

I am developing a page where the user can create a new Product.

Every Product has a Product Model which has some fields like :id, :name, :description, etc.

In this Product page, I have a <select> where the user will be able to pick a Product Model. What I am wanting to do is, when the user select a Product Model, the page should update displaying the selected Product Model details.

How can one do that?

Upvotes: 0

Views: 180

Answers (1)

Sovalina
Sovalina

Reputation: 5609

Example of what you can do with javascript (based on a select change):

First define a route on collection, for a ProductModel custom method. Let's call it find :

resources :product_models do
  get 'find', on: :collection  #=>output: /product_models/find/:id
end

In ProductModelsController make the find method respond to js format:

def find
  @product_model = ProductModel.find(params[:id])
  respond_to { |format| format.js }
end

Assuming you have jQuery, in your application.js (or other custom js file you want), create the ajax call to find the product_model:

$(document).on('turbolinks:load', function() {
  $('#product_product_model_id').on('change', function(){ //<-- the id selector is returned by simple_form
    $.ajax({
      type: "GET",
      url: "/product_models/find/?id=" + $(this).val(),
      success: function(data) {
      },
      error: function(jqXHR) {
        console.error(jqXHR.responseText);
      }
    })
  })
})

In your Product new view, under your form, render a partial named, for example, "selected_product_model":

#new.html.erb
<% simple_form_for @product do |f| %>
  #... the form
  f.association :product_model
<% end %>

<div>
  <%= render partial: 'selected_product_model' %>
</div>

And in the partial, create the html selectors where the data will be displayed:

#_selected_product_model.html.erb
<p id="pm-id"></p>
<p id="pm-name"></p>
<p id="pm-desc"></p>

Then create your find.js.erb file (in views > product_models folder) to update your partial on select change:

# @product_model comes from the controller find#product_models
$('#pm-id').html("ID: <%= j @product_model.id.to_s %>")
$('#pm-name').html("Name: <%= j @product_model.name %>")
$('#pm-desc').html("Description: <%= j @product_model.description %>")

Of course, it's just a basic example of what you can do with ajax in rails, you can custom the way you want to display your data or add some conditions to prevent errors.

Upvotes: 2

Related Questions