Passing a variable with render

When we want to share a form we make a partial of it:

app/views/users/_fields.html.erb

<%= f.label :name %>

<%= f.text_field :name %>

<%= f.label :password %>

<%= f.password_field :password %>

and then we implement the code:

app/views/users/new.html.erb

<%= form_for(@user) do |f| %>
<%= render ‘fields’, :f => f %>

<%= f.submit “Submit” %>
<% end %>

in the case of a shared error messaging system:

app/views/shared/_error_messages.html.erb

<% if object.errors.any> %>

<%= pluralize(object.errors.count, “error”) %> are present. And those
are :

    <% object.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>

<% end %>

and we pass the render code:

<%= render ‘shared/error_messages’, :object => f.object %>

inside the form_for helper

My question is why in the case of error_messages partial we pass the
f.object and not just f since f is the object itself
and in the case of field partian (that holds the form) we pass just
f ?

Wouldnt it work if we wrote <%= render ‘shared/
error_messages’, :object => f %> ?
what is the difference?

You dont want to pass the whole f object( the form helper object), when
you
only need the AR instance to loop the object’s validation errors. f has
methods of its out like text_field , check_box, etc… you dont want to
pass f to generate the error list when the instance of the AR is the one
with has the method errors. In your example @user is the same as
f.object so
you could have done

<%= render ‘shared/error_messages’, :object=> @user %>

This makes clear what is it that you are passing to the errors loop. AR
instances have a method like this

@user.errors

so you can do

@user.errors.each do

on the other hand , f is a form helper object, that has methods like

f.text_field
f.text_area

I hope this helps.

ok i think i got it now
thank you