简体   繁体   中英

difference between text_field and text_area in form_for

So I have seen examples of text_field and text_area being used in forms like this:

<%= form_for :account do |a| %>
    Name: <%= a.text_field :name %><br />
    Password: <%= a.text_area :password %><br />
    Password Confirmation: <%= a.text_field :password_confirmation %><br />
<%= a.submit %>
<% end %> 

I don't understand the difference, though. Is it necessary for a beginner Rails developer to understand the difference?

I found some explanations in the API which I don't understand - perhaps somebody can take a look and let me know what is going on.

For "text_area":

text_area(object_name, method, options = {})

Returns a textarea opening and closing tag set tailored for accessing a 
specified attribute (identified by method) on an object assigned to the template 
(identified by object). 
 Additional options on the input tag can be passed as a hash with options.

Then, for "text_field":

  text_field(object_name, method, options = {}) Link

    Returns an input tag of the “text” type tailored for accessing a specified 
attribute (identified by method) on an object assigned to the template 
(identified by object). Additional options on the input tag can be passed 
as a hash with options. These options will be tagged onto the HTML as an 
HTML element attribute as in the example shown.

a.text_field :name is parse to the following html

<input type="text" name="name">

a.text_area :name would parse to something like:

<textarea rows="4" cols="50">

</textarea>

depending on the options passed.

The simplest way of looking at it is text_field gives you a place for a single line of text, where text_area gives an area for multiple lines.

you can pass a hash of options to the text_area helper to specify the number of rows and columns.

In the example you give above, it would be poor practice to use either text_field or text_area for passwords, you'd be better to use a.password_field

thats a good answer - funny when googling this and looking for a spot on example - after i read the response above - i looked at my code and realized it was an even better example

 <%= f.label :name %>
 <%= f.text_field :name %><br />
 <%= f.label :bio %>
 <%= f.text_area :bio %><br />

makes sense, name would only need a single line (unless you have a super long name) where as bio, would need multiple lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM