How to render partial on the same page after clicking on link_to with AJAX
You basically want to use AJAX to display a customer's details. For this you can use the remote: true
option provided by rails for the link_to
helper. What we are going to do next :
Create a div that will contain the loaded data. In this case
div#current_customer
Add
remote: true
to your link :<td><%= link_to 'Show', customer, remote: true %></td>
Name your partial
customers/_show.html.erb
(don't forget the_
so it can be called as a partial) :<p> <strong>Name:</strong> <%= @customer.name %> <%= @customer.id %></p><%= link_to 'Edit Customer', edit_customer_path(@customer) %> |<%= link_to 'Back', customers_path %> # You should remove this link
Respond to Javascript in the
show
method inCustomersController
:respond_to do |format| format.js {render layout: false} # Add this line to you respond_to blockend
Create your
show.js.erb
view, which is going to handle the front-end changes whenrespond_to :js
is gonna be called (In this case triggered byremote: true
)Tell
show.js.erb
what it must do (Replace#current_customer
content with your partial, using the right@customer
) :
customers/show.js.erb
$("#current_customer").html("<%= escape_javascript(render partial: 'customers/show', locals: { customer: @customer } ) %>");
customers/index.html.erb
Name Actions<div id="current_customer"> # This will will contain the partial </div>