0
0
RailsHow-ToBeginner · 3 min read

How to Create Form in Rails: Syntax and Example

In Rails, you create forms using the form_with helper method, which generates HTML form tags linked to your model or URL. Inside form_with, you use form fields like text_field and submit to build the form inputs and buttons.
📐

Syntax

The basic syntax of a form in Rails uses the form_with helper. It can be linked to a model or a URL. Inside the block, you add form fields and buttons.

  • form_with(model: @object): Creates a form tied to a model instance.
  • form_with(url: some_path): Creates a form that submits to a specific URL.
  • form.text_field :attribute: Adds a text input for the model's attribute.
  • form.submit: Adds a submit button.
ruby
form_with(model: @post) do |form|
  form.text_field :title
  form.text_area :content
  form.submit "Save"
end
💻

Example

This example shows a simple form for a Post model with title and content fields. It uses form_with to generate the form and submit button.

erb
<!-- app/views/posts/new.html.erb -->
<%= form_with(model: @post) do |form| %>
  <div>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :content %><br>
    <%= form.text_area :content %>
  </div>
  <div>
    <%= form.submit "Create Post" %>
  </div>
<% end %>
Output
<form action="/posts" method="post"> <div> <label for="post_title">Title</label><br> <input type="text" name="post[title]" id="post_title"> </div> <div> <label for="post_content">Content</label><br> <textarea name="post[content]" id="post_content"></textarea> </div> <div> <input type="submit" value="Create Post"> </div> </form>
⚠️

Common Pitfalls

Common mistakes when creating forms in Rails include:

  • Not passing a model or URL to form_with, which causes the form not to submit correctly.
  • Forgetting to permit parameters in the controller, leading to errors when saving data.
  • Using form_tag instead of form_with in modern Rails, which is legacy.
  • Not including labels for accessibility.
erb
Wrong:
<%= form_with do |form| %>
  <%= form.text_field :name %>
  <%= form.submit %>
<% end %>

Right:
<%= form_with(model: @user) do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>
  <%= form.submit %>
<% end %>
📊

Quick Reference

Here is a quick summary of key form helpers in Rails:

HelperPurpose
form_with(model: @object)Creates a form linked to a model instance
form_with(url: path)Creates a form that submits to a specific URL
form.text_field :attributeAdds a text input field
form.text_area :attributeAdds a multi-line text area
form.label :attributeAdds a label for an input
form.submitAdds a submit button

Key Takeaways

Use form_with with a model or URL to create forms in Rails.
Always include labels for accessibility and clarity.
Permit parameters in your controller to allow form data saving.
Avoid legacy helpers like form_tag in new Rails apps.
Test your form to ensure it submits data correctly and renders inputs.