Introduce a decorator using a gem draper. Make a note of the clogged part when introducing this Gem.
・ Ruby 2.6.4 ・ Rails 5.2.3
About the role of Decorator and Draper Summary of how to use Draper Prepare a Decorator to display Rails View to help Helper and Model
First, install Gem.
Gemfile.
gem 'draper'
You can use draper by typing the following two lines into the terminal.
$ bundle install
$ rails generate draper:install
First, create app/decorators/user_decorator.rb.
$ rails generate decorator User
This time we will create a method to call the full name. last_name and first_name have been added to the columns of the User model in advance.
app/decorators/user_decorator.rb
class UserDecorator < Draper::Decorator
delegate_all
def full_name
"#{object.last_name} #{object.first_name}"
end
end
Displays the currently logged in user (current_user) with the full name.
#In the View file where you want to use the method
<%= current_user.decorate.full_name %>
With the above procedure, you have installed the decorator using gem'draper'. If you get an error in this flow, please try to solve it while looking at the reference materials.
Recommended Posts