I will refer to the following article. https://pikawaka.com/rails/form_with
form_with is a ** helper method ** for sending information via rails. By using form_with, you can easily create the HTML required for the input form.
What is a helper method? In Rails, it is a general term for methods used mainly for making HTML tags appear in views and processing text.
The advantage of helper methods is ** Simplified description such as path specification and Ruby embedding Can solve security problems ** Etc.
** Basic writing style **
How to write form_with when not saving to database
<%= form_with url: "path" do |form| %>
#Form contents
<% end %>
How to write form_with when saving to database
<%= form_with model:Model class instance do|form| %>
#Form contents
<% end %>
For example, the following code will display this form in your browser.
ruby:new.html.erb
<%= form_with(model: @user, url: entrys_path, local: true) do |form| %>
<h1>Enter your user name</h1>
<div class="field">
<%= form.label :name, "Name (full-width)" %>
<%= form.text_field :name %>
</div>
<% end %>
By the way, with the function of form_with, If the instance of the model class passed as an argument is an instance with contents, the process is assigned to the update action.
On the contrary, if the instance of the model class passed as an argument is an instance with no contents, the process will be distributed to the create action.
Since the process is automatically distributed, the method is not specified.
** How to write an advanced form **
When adding options
<%= form_with model:Model class instance,option, do |form| %>
Form contents
form.html tag name: column name
Option name | Description |
---|---|
url option | Specify the path of the request to send the form information. |
method option | Specify the HTTP method of the request to send the form information. The initial value of the option is: post, so it can be omitted when specifying the post method. |
local option | Specifies whether to disable remote transmission. If set to true, it will be invalid. |
html tag method | Usage |
---|---|
form.text_field | One-line text posting form |
form.text_area | Multi-line text post form |
form.number_field | Generate a numeric input box |
form.search_field | One-line search form |
form.email_field | Generate email address input box |
form.check_box | Generate checkbox without database information |
form.collection_check_boxes | Generate checkboxes based on database information |
form.select | Create a choice |
form.collection_select | Generate choices based on database information |
form.file_field | Generate file selection box |
form.datetime_field | Generate date and time input field |
form.date_select | Generate date selection box |
form.hidden_field | Hidden form |
form.submit | Generate submit button |
Recommended Posts