search
LoginSignup
12

More than 5 years have passed since last update.

posted at

updated at

draperでdecorates_associationしたmodelは、object無しで呼ぶ

数時間詰まったので、ここで共有します。

注意点

decorate_associationdecorate_accosiationsdecorateしたmodelobject.無しで呼ばないと、decoraterで定義したmethodを呼べません。

app/models/inquiry.rb
class Inquiry < ActiveRecord::Base
  has_many :messages, dependent: :destroy
end
app/models/message.rb
class Message < ActiveRecord::Base
  belongs_to :inquiry
end
app/decorator/inquiry_decorator.rb
InquiryDecorator < Draper::Decorator
  delegate_all
  decorate_associations :messages#, with: MesssageDecorator

  def deco_last_message_created_at
    #object.messages.last.deco_created_at # undefined error
    messages.last.deco_created_at # object. が不要
  end
end
app/decorator/message_decorator.rb
MessageDecorator < Draper::Decorator
  delegate_all

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

以上です。
誰かのお役に立てれば幸いです。

参考

https://github.com/drapergem/draper
http://www.rubydoc.info/github/drapergem/draper/Draper/Decorator

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
What you can do with signing up
12