Basic question about form_for

The form_for api docs have this example:

<% form_for :person, @person, :url => { :action => “update” } do |f| %>

Can someone explain the function of :person and @person? I guess that
@person was set in the controller.
But then what is :person? Why do I need both?

The form_for api docs have this example:

<% form_for :person, @person, :url => { :action => “update” } do |f| %>

Can someone explain the function of :person and @person? I guess that @person was set in the controller.
But then what is :person? Why do I need both?

Try it and then view the source to see the result… using this example:

<% form_for :person, @person, :url => { :action => “update” } do |f| %>
First name: <%= f.text_field :first_name %>
Last name : <%= f.text_field :last_name %>
Biography : <%= f.text_area :biography %>
Admin? : <%= f.check_box :admin %>
<% end %>

You’d end up with form names of:

person[first_name]
person[last_name]
person[biography]
person[admin]

That takes care of :person. @person is what is used to populate those
fields with default values…

-philip

Uh… Weird. I’ve been using

form_for :model_name, :url => {:action => :whatever} do |f|
end

and it works fine. I don’t know how/why I started doing it this way but
it
does work. Does Edge Rails use form_for differently? Is @person designed
so
you could use a different model there? I’m genuinely puzzled by this.

RSL

Russell N. wrote:

Uh… Weird. I’ve been using

form_for :model_name, :url => {:action => :whatever} do |f|
end

and it works fine. I don’t know how/why I started doing it this way but
it
does work. Does Edge Rails use form_for differently? Is @person designed
so
you could use a different model there? I’m genuinely puzzled by this.

RSL

form_for allows you to use any object, not just an instance variable.
This allows you to do something like:

#some_view
<% @foobars.each do |fb|
<% form_for :foobar, fb %>
<%= f.text_field :title %>
<%= submit_tag ‘Save Foobar!’ %>
<% end %>
<% end %>

:foobar, is a string or symbol use to name the form fields. So when
submitted, all form fields will be in params[:foobar]. The second
argument, fb, is the object whose values will be shown in the form when
the page loads.

You can leave off the second argument:

<% form_for :foo do |f| %>

And the helper will assume you want an instance variable of the same
name, so will use @foo for generating the default form values.

So these two lines are the same:

<% form_for :foo do |f| %>
<% form_for :foo, @foo do |f| %>

But the second allows you to do tricky things like:

<% form_for :foo, my_crazy_local_var do |f| %>

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs