What are the defaults in Rails for connecting models to partials?

101 Views Asked by At

In Rails 7, there appears to be some defaults that connect models to partials. If so, can someone point me to the documentation?

I am working through the "Depot" demo in Sam Ruby's "Agile Web Development with Rails 7". This demo uses a generator to build a scaffold for a "Product" table. This block appears in index.html.erb:

  <div id="products" class="min-w-full">
    <%= render @products %>
  </div>

and there is a file named _product.html.erb in the views directory.

So, there must be a convention that maps an array of model objects to a partial of the same name; but, I can't find anything that documents that --- including on this page: https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action

I do see that you can pass an object to render if that object responds to render_in; but, Product does not appear to either implement or inherit this method.

Normally, I'd be happy using the "obvious" behavior; but, I'm teaching a class on Rails, and I'd like to be able to explain this "magic" (or at least know where it is documented).

2

There are 2 best solutions below

0
Les Nightingill On BEST ANSWER

It's documented under Rendering Collections:

There is also a shorthand for this. Assuming @products is a collection of Product instances, you can simply write this in the index.html.erb to produce the same result:

<h1>Products</h1>
<%= render @products %>

Rails determines the name of the partial to use by looking at the model name in the collection.

I realize that's not the documentation for the source code, if that's what you're looking for, but I think you can regard it as authoritative.

1
Alex On

to_partial_path method defines what partial is rendered, which is part of the rendering process:

class Product < ApplicationRecord
  def to_partial_path
    "some/partial"
  end
end       

Which means render @product will render some/_partial.