Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea in Rails form

I have an HTML form in Rails:

<form id="my_form" action="submit">
  Title: <input type="text" name="title"> 
</form> 

I want to add a new field using a <textarea>:

Comment: <textarea rows="4" cols="50"></textarea>

Is it okay if put this into the form? How can I access the value that the user fills in?

like image 366
JJ Beck Avatar asked Oct 21 '25 19:10

JJ Beck


2 Answers

Unless you have some good reason not to, you should really use the action view helpers provided by rails.

The form helpers provide resource-oriented methods which create a form and a scope around a specific model object, but this does not suit your case.

What you want instead is to use to use the generic form tag helpers, which include generic versions of the form methods not tied to any specific model or record, e.g.: form_tag, text_field_tag, text_area_tag, etc. These methods do not require you to pass a record to them or define them in terms of a specific model; you can define arbitrary actions, ids etc., like so:

<%= form_tag "submit", :id => "my_form" do -%>
  Title: <%= text_field_tag "title" %>
  Comment: <%= text_area_tag "comment", :rows => 4, :cols => 50 %>
  <%= submit_tag "Submit" %>
<% end -%>

Note that you had no name or id on your textarea, so I've arbitrarily assigned them the string "comment", which makes sense for the case.

In terms of accessing the value(s) the user enters, you just do it like any other form, i.e. in your controller you just access params[:title], params[:comment] etc.

like image 175
Chris Salzberg Avatar answered Oct 24 '25 10:10

Chris Salzberg


if you use form_tag helper then you can create textarea as follows:

      text_area_tag(:comment, nil, :rows => 5, :cols => 15)

Your code for form_tag would be as follows:

  <% form_tag :action => :submit do %>
  <%= label_tag "Title" %>
  <%= text_field_tag :title %>
  <%= text_area_tag :comment, nil, :rows => 5, :cols => 15 %>
  <%= submit_tag "submit" %>
  <% end %>

You should have method called submit in your controller. In that method you can access comment using params. For example comment can be accessed as params[:comment]

For more info see this: forms_and_tags

like image 41
dealer Avatar answered Oct 24 '25 09:10

dealer