LoginSignup
3
2

More than 5 years have passed since last update.

DraperでAssociationする方法

Last updated at Posted at 2019-03-21

概要

DraperでAssociationして、親モデルからDecorateされた子モデルを取得する時に少しハマったので、手順を残します。

モデルの内容

BookとReviewが1対多の関係になっている。

class Book < ApplicationRecord
  has_many :reviews
end

class Review < ApplicationRecord
  belongs_to :book
end

やりたいこと

book.reviewsでアクセスした時のreview.created_atをフォーマットした状態にしたい。

  • Decorateしていない状態だとこうなる。
@book = Book.find(1)
@book.reviews.first.created_at
=> Sun, 10 Mar 2019 06:14:33 UTC +00:00
  • Decorateしてフォーマットした時刻を出力したい。
@book = Book.find(1).decorate
@book.reviews.first.created_at
=> "2019/03/10 06:14"

やり方

  • BookDecorator内でReviewsDecoratorをアソシエーションする。
class BookDecorator < Draper::Decorator
  delegate_all
  decorates_associations :reviews
  # もし1対1の場合は以下のように設定する。
  decorates_association :review
end
  • ReviewDecoratorにデコレートする内容を書く。
class ReviewDecorator < Draper::Decorator
  delegate_all

  def created_at
    return object.created_at.strftime("%Y/%m/%d %H:%M")
  end
end

結果

フォーマットされた出力結果が得れた。

@book = Book.find(1).decorate
@book.reviews.first.created_at
=> "2019/03/10 06:14"
3
2
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
3
2