14
12

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 5 years have passed since last update.

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

Last updated at Posted at 2015-03-04

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

#注意点
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

14
12
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
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?