Rails not able to find partial

730 Views Asked by At

I have a folder structure like

project/app/views/api/users/_user.json.jbuilder

The error is

Searched in:
  * "/Users/name/Desktop/etc/etc/project/app/views"

ActionView::MissingTemplate - Missing partial api/users/_user.json.jbuilder with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}.

I'm trying to render

  <script type="text/javascript">
    window.currentUser = <%= render("api/users/user.json.jbuilder",
        user: current_user).html_safe %>
  </script>

The exact same code worked in Rails 5.xx, but I'm on Rails 7.xx now and I'm stuck on this error.

2

There are 2 best solutions below

2
TedTran2019 On

In Rails 7, including the extension on the file results in an error.

<%= render partial: "api/users/user", 
    formats: [:json], 
    handlers: [:jbuilder],
    locals: { user: current_user } %>

Works and Rails is able to find the partial. The error message is pretty useless in this case because it just seems like you're doing it right. Also, I can't find any documentation at all on the options hash you're supposed to pass to render partial. My Github Copilot just auto-completed it for me, then I scoured the internet trying to find information pertaining to it but couldn't.

I'm assuming you just look at the error message

{:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}

Then realize the options are locale, formats, variants, handlers?

Answer found here Rails 7 missing partial

0
FirstZion On

To build on the answer above. If you were to replace

  <script type="text/javascript">
    window.currentUser =
      <%= render("api/users/user.json.jbuilder", 
        user: current_user).html_safe %>      
  </script>

with

<script
  <%= render partial: "api/users/user", 
    formats: [:json], 
    handlers: [:jbuilder],
    locals: { user: current_user } %>
</script>

You would still run into a pretty annoying error because the latter doesn't have the html safe tail

.html_safe!

the way I understand it is that html safe is frowned upon and should be substituted for sanitize to get the same result as the original code.

<script id="bootstrap-current-user" type="text/javascript">       
  window.currentUser = 
  <%= sanitize render partial: 'api/users/user',
    formats: :json,
    handlers: :jbuilder,
    locals: {user: current_user} %>      
</script>

If you don't sanitize the partial call before assigning it to the window.current user then you will get a syntax error from jbuilder trying to use &quot instead of a "

Here is the html_safe documentation.

Here is the sanitation documentation.