What's the replacement for .js.erb in Rails 7?

Viewed 137

As of Rails 7, .js.erb is deprecated. I used it extensively in a Rails 6 application I've been working on to render a partial on the current page upon the click of a link_to, which was marked as remote. Since I updated my application to Rails 7, clicking the link acts like it's not remote, and Rails gives me an error saying there's a missing template (which there is because I use partials for that action).

I've been doing research about this and I haven't been able to find any recent advice; everything just says use .js.erb. I understand the reason it was taken out has to do with CSP, but it's a bit frustrating since it was so convenient.

Anyway, I'm sure other people are having this problem, so what are we expected to do in replacement of using .js.erb? I saw something about Hotwire but none of the docs I've seen talk about partials, so I'm having trouble figuring it out.

1 Answers

The replacement for .js.erb responses in controllers is to use .turbo_stream.erb responses.

// .js.erb
$("#element").html("Hey this is the new html")

// .turbo_stream.erb
<%= turbo_stream.update("element") do %>
  Hey this is the new html
<% end %>

and in the controller switch the respond_to from js to turbo_stream

// some_controller.rb
def update
  respond_to do |format|
    format.turbo_stream
  end
end
Related