About helper method, I read Perfect Ruby on Rails [enhanced revised edition] and summarize what I personally learned. ..
A handy method to help you develop with view templates. Some generate HTML and some generate URLs.
If the path starting with / excluding the domain and port with the Prefix value + _path
when displaying the routing is set to the Prefix value + _url
, the complete URL including the domain etc. is returned.
If the path has a fluctuating value such as ": id", specify the value in hash format as an argument.
Used when specifying the path or URL with url_for, link_to, or redirect_to.
In the case of the following routing, the following path and URL are returned.
routing
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
edit_user GET /users/:id/edit(.:format) users#edit
** Return path or URL **
/users
/users/1
http://www.example.com/users/1/edit
url_for Helper method for building web application paths. You can use the routing definition without writing the string directly. Use it when you just want to get the URL.
url_for(users_path)
#=> /users
link_to
link_to is a helper method that generates an a tag.
Use when you want to set a link on the screen by utilizing the definition on the routing with _path
or _url
.
link_to('Edit', edit_user_path(id: 1))
#=> <a href="/users/1/edit">Edit</a>
time_ago_in_words A helper method that makes it easy for humans to see how much space there is between a certain time and the current time. It seems that it can be used in a service that displays the last login date and time.
time_ago_in_words(Time.current)
#=> less than a minute
time_ago_in_words(Time.current + 3.days)
#=> 3 days
number_with_delimiter A helper method that separates long numbers into commas. You can optionally change the delimiter.
number_with_delimiter 1234567890
#=> 1,234,567,890
number_with_delimiter 1234567890, delimiter: '@'
#=> 1@234@567@890
Rails has various other helper methods, so before you implement it yourself, [Rails Guide](https://railsguides.jp/action_view_overview.html#action-view%E3%81%AE% E3% 83% 98% E3% 83% AB% E3% 83% 91% E3% 83% BC% E3% 83% A1% E3% 82% BD% E3% 83% 83% E3% 83% 89% E3% 81% AE% E6% A6% 82% E8% A6% 81) seems to be a good reference.
If the Rails built-in helper method doesn't suit your needs, implement the helper method yourself. Modules for defining helper methods are defined under the directory "app / helpers". File for helper corresponding to the controller such as "app / helpers / application_helper.rb" if it is used for the whole application, and "app / helpers / users_helper.rb" if it is used for each controller. prepare.
Example) Helper method to convert full-width English characters to half-width
app/helper/application_helper.rb
module ApplicationHelper
def to_hankaku(str)
str.tr('A-Za-z', 'A-Za-z')
end
end
to_hankaku('Ruby')
#=> Ruby
Perfect Ruby on Rails [Augmented and Revised Edition]
Recommended Posts