Partial to Ajax
I have been building a new project and getting creative with views. I am working with bootstrap and jquery to develop tabbed displays, and in the process have been gleaning a deeper understanding of rails routes, controllers, and assets. Using Ajax to load partials into rails views is a three part process:
1. In the View, Add a Link
<%= link_to "Show my partial", path_to_controller, remote: true %>
The key difference in the syntax for this link is “remote: true”, which signals to the controller action to respond using ajax, not html.
2. Create a Partial
<div> <%= form_for @model do |f| %> <%= f.label :my_text_field, "Text Field Label" %> <%= f.text_area :my_text_field %> <%= f.submit "New", class: "btn btn-primary" %> <% end %> </div>
3. In the Controller Action, Add a js Response
def my_action respond_to do |format| format.js end end
3. Create a my_action.js.erb File to Shape the Ajax Response
app/views/users/ ├── _my_partial.html.erb ├── edit.js.erb ├── show.html.erb
Voila! When you click the link in your view the partial is loaded using Ajax.