6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails]gem draperを使用して、decoratorを導入する方法

Posted at

目的

gem draperを使用して、decoratorを導入する。
このGemを導入するときに詰まった部分をメモとして残す。

開発環境

・Ruby 2.6.4
・Rails 5.2.3

参考資料

Decoratorの役割とDraperについて
Draperの使い方 まとめ
Rails Viewの表示のためにDecoratorを用意してHelperとModelを助ける

導入手順

①gem 'draper'をインストールする。

まずはGemをインストールします。

Gemfile.
gem 'draper'

以下の2行をターミナルに入力すれば、draperを使うことができます。

$ bundle install
$ rails generate draper:install

②デコレーターを作成

まず、app/decorators/user_decorator.rb を作成します。

$ rails generate decorator User

今回はフルネームを呼び出すメソッドを作っていきます。
last_nameとfirst_nameは、事前にUserモデルのカラムに追加してあります。

app/decorators/user_decorator.rb
class UserDecorator < Draper::Decorator
  delegate_all

  def full_name
    "#{object.last_name} #{object.first_name}"
  end
end

③ 作ったメソッドをViewファイルで呼び出す。

現在ログインしているユーザー(current_user)をフルネームで表示します。

# メソッドを使いたいViewファイルにて

<%= current_user.decorate.full_name %>

以上の手順でgem 'draper'を使って、decoratorを導入できました。
この流れでエラーが出てしまった場合は、参考資料など見ながら解決してみてください。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?