maria
maria

Reputation: 213

Using the textarea helper in Rails forms

Why does this code show an error in text area?

<%= form_for(:ad, :url => {:action => 'create'}) do |f| %>
  <%= f.text_field(:name) %>
  <%= f.text_area_tag(:text, "", :size => "50x10") %>
  <%= submit_tag("Submit") %>
<% end %>

Upvotes: 21

Views: 34037

Answers (2)

user229044
user229044

Reputation: 239571

The FormHelper method is text_area, not text_area_tag.

Use either of the following:

<%= f.text_area(:text, size: '50x10') %>

or:

<%= text_area_tag(:ad, :text, size: '50x10') %>

Upvotes: 34

Adam Lassek
Adam Lassek

Reputation: 35515

The f variable that you are creating in the first line is a reference to your FormBuilder. By default it references ActionView::Helpers::FormBuilder or you can create your own.

The FormBuilder helper for textareas is called text_area. FormBuilder helpers are smarter than regular HTML helpers. Rails models can be nested logically, and your forms can be written to reflect this; one of the primary things FormBuilder helpers do is keep track of how each particular field relates to your data model.

When you call f.text_area, since f is associated with a form named :ad and the field is named :text it will generate a field named ad[text]. This is a parameter convention that will be automatically parsed into a Hash on the server: { :ad => { :text => "value" } } instead of a flat list of parameters. This is a huge convenience because if you have a Model named Ad, you can simply call Ad.create(params[:ad]) and all the fields will be filled in correctly.

text_area_tag is the generic helper that isn't connected to a form automatically. You can still make it do the same things as FormBuilder#text_area, but you have to do it manually. This can be useful in situations that a FormBuilder helper isn't intended to cover.

Upvotes: 5

Related Questions