Search code examples
ruby-on-railsviewinstancerenderpartial

About rails render argument


From edit.html.erb view,

<%= render 'form', post: @post, url: authors_post_url(@post) %>

what is meant by the second argument post: @post? Is this naming @post to post to be used in the partial _form ?

From _form.html.erb partial file,

<%= form_for(post, url: url) do |f| %>
  <% if post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
      <ul>
      <% post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <% if @post.persisted? %>
    <%= link_to 'Show', @post %>
  <% end %>
<% end %>

As seen above, @post are still being used which defeats the purpose of naming @post to post in the render line above.


Solution

  • As seen above, @post are still being used which defeats the purpose of naming @post to post in the render line above.

    Exactly! That's sloppy coding on someone's part. The purpose of that syntax is to abstract the partial from its environment, so that it doesn't have to rely on @post being available. On another page, the partial may be rendered like this, for example:

     <%= render 'form', post: Post.new, url: authors_posts_url) %>
    

    If the partial follows rules and only uses its local post, it'll keep working. But the one from your question, it will break.