0

I have a (simple) question for my own curiosity: I'd like to find out how Rails prefill forms with posted values like... you know, when there's a validation error on some models' attributes then you do something like "render :edit" and the form is magically prefilled.

What exactly are the mechanisms that Rails use to do such a thing? I didn't manage to find any documentation on this subject and I'd like to understand the magic.

So if someone can give me some explanations on this subject, I'll be glad to read that!

Thanks!

[Edit] And a subsidiary question: when a model inherits from another (STI) do we have to do something in particular to prefill forms?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Kulgar
  • 1,855
  • 19
  • 26

1 Answers1

1

You are mostly using the form_for helper in this style:

<%= form_for @person do |f| %>
  <!-- Some more stuff here -->

  <%= f.text_field :first_name %><br />

  <!-- Some more stuff here -->
<% end %>

What this essentiall does is, it generates a text field that is filled with the value of @person.first_name.to_s. When an error happens, @person.first_name is filled with the errornous value. If you create a person (@person = Person.new), then @person.first_name.to_s is "".

So rails just fills the text field with the value, the attribute has.

f by the way is a rails FormBuilder. It's methods are documented here, if you want to take a closer look at the source.

iblue
  • 29,609
  • 19
  • 89
  • 128
  • Thanks a lot! So if I understand correctly the source, this method: "submit_default_value" is the one that prefills forms, am I right? And what about single table inheritance, is there something to do in particular to make Rails prefills forms after a failed submit of a child model? – Kulgar Jul 30 '12 at 09:51