I summarized how to write the link_to method of rails.
The link_to method is the helper method used in the view. It is used when you want to display the link, and it generates the a tag of html. You can display the link by passing the character string to be displayed as a link and the link destination as arguments to the link_to method. Below, I will introduce how to write the basic source code of the link_to method.
--Link text as the first argument --Specify the path and URL in the second argument
You can create a link by passing these as arguments.
--When using URL
<%= link_to 'Yahoo', 'http://www.yahoo.co.jp/' %>
--When using a path
<%= link_to ‘User list’, ‘/users/index’ %>
If you want to create a link within the same application, use: Specify the route name set in "config / routes.rb" with "_path" added as the link destination. Use the following command to check the name of the routing. Run it in the application you created.
rails routes
Prefix Verb URI Pattern Controller#Action
incomes POST /incomes(.:format) incomes#create
new_income GET /incomes/new(.:format) incomes#new
edit_income GET /incomes/:id/edit(.:format) incomes#edit
income PATCH /incomes/:id(.:format) incomes#update
PUT /incomes/:id(.:format) incomes#update
DELETE /incomes/:id(.:format) incomes#destroy
For example, if you want to paste a link to the new action (new creation screen) of income_controller, write as follows.
--When using Prefix
<%= link_to 'Create New', new_income_path %>
--When using URI Pattern
<%= link_to 'Create New', ‘/incomes/new’ %>
Some of the above URI patterns include id, which indicates ** which "income" to set the link to the edit screen **. By passing the id of income as an argument to "edit_income_path", the link destination will be set based on the id of the income data.
HTTP method can be specified in the argument of link_to method. ** If nothing is specified, it will be GET **. The way to write is as follows.
<%= link_to ‘Delete’, income_path(params[:id]), method: :delete %>
You can also set the id attribute and class attribute.
The link_to method can also be described using the do ~ end block as shown below.
<%= link_to income_path, class: 'hoge' do %>
<div>a</div>
<h4>b</h4>
<p>c</p>
<% end %>
Elements in link_to do ~ end can be linked at the same time.
https://udemy.benesse.co.jp/development/web/link-to.html
Recommended Posts