ruby-on-railsrubyactionviewhelper

Difference between render 'posts' and render posts (without quotes)


I was going through a video and where he was rendering something like below example:

<div>
 <%= render posts %> # no quotes to posts
</div>

Though he has even created a partial with _posts.html.erb, he is calling with quotes to posts.

Though he has mentioned something about it like it calls, active record model, then class and then something...i could not understand it properly. Can anyone explain clearly this with simple example.


Solution

  • With quotes then you are explicitly rendering a partial of that name. Without quotes something quite interesting is happening. posts (without quotes) is a variable that will be an activemodel list of records.

    Now what the call to render does is it will look at the type of each of the models and then find the correct partial for the model (which will be the name of the model camel_cased) and render each one in turn.

    EDIT:

    If you have a model called Post and you assign some of those records to a variable (he uses posts I assume but I'll use foo to disambiguate) like so:

    foo = Post.all
    

    then by calling render foo the render function will see that you have an activerecord collection of records, it will then check the model associated with these records (Post in our example) and will loop through all of them rendering them to a partial called _post.html.erb with a local variable for each record assigning the record to post.

    <%= render foo %>
    

    is equivalent to:

    <% foo.each do |my_post| %>
      <%= render partial: "post", locals: {post: my_post} %>
    <% end %>