Ruby On Rails Form

Ruby on Rails forms: get up and running quickly with an example of using Rails forms to create, update, and delete data.

Ruby on Rails Form

Building a form with Ruby on Rails can be done using the form_for tag. This tag creates a form with the specified model and the given parameters and generates the necessary HTML code for the form. The following example shows how to create a basic form with a text field and a submit button:


<%= form_for(@post) do |f| %>
  <div>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %>

This will generate a basic form with a text field for the title and a submit button. The form will be submitted to the specified controller action when the user presses the submit button. The form will also include CSRF protection to prevent cross-site request forgery (CSRF).

The form_for tag can also be used to create more complex forms. For example, the following code will create a form with a text field, a text area, and two submit buttons:


<%= form_for(@post) do |f| %>
  <div>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.label :body %>
    <%= f.text_area :body %>
  </div>
  <div>
    <%= f.submit 'Save' %>
    <%= f.submit 'Cancel' %>
  </div>
<% end %>

This will generate a form with a text field for the title, a text area for the body, and two submit buttons for saving and canceling the form. The form will be submitted to the specified controller action when either of the submit buttons is pressed.

Using the form_for tag, it is possible to quickly and easily create forms with Ruby on Rails. The tag simplifies the process of creating forms and ensures that the forms are properly generated with the necessary HTML code and CSRF protection.

Answers (0)