Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
12
Help us understand the problem. What are the problem?