Fetching a partial on click

I’d say this is a great approach. In my experience it’s very common. As I mentioned, it can be done in such a way that the Stimulus controller is generic and reusable, and the backend code is obviously trivial, so it’s win win all around.

You can simplify the Stimulus controller even more if you leverage Rails’ Unobtrusive Javascript to make the actual calls to the controller by leveraging remote: true on your links.

For example:

index.html.erb

<ul>
<% @customers.each do |customer| %>
  <li data-controller="renderer">
    <%= link_to customer.name, customer_detail_path(customer), data: { remote: true, action: 'ajax:success->renderer#render' }  %>
    <span data-target="renderer.display"></span>
  </li>
<% end %>
</ul>

renderer_controller.js

import { Controller } from 'stimulus'

export default class extends Controller {
  static targets = ['display']

  render(evt) {
    this.displayTarget.innerHTML = evt.detail[0].body.innerHTML
  }
}

You’ve effectively introduced a single line of JS here that can be reused in many situations by leveraging the JS that’s already packaged in Rails. It’s an all around pretty elegant solution if you ask me!

One thing I’ll point out, I did reference a customer_detail_path here, hinting at using a CustomerDetailsController rather than bundling the details response in with the CustomersController. Purely optional, but it follows this advice from DHH and I’ve found it to be helpful in keeping my controllers dead simple.

6 Likes