LoginSignup
6
6

More than 5 years have passed since last update.

ActiveRecord Associationのdecorate

Last updated at Posted at 2014-06-25

今更ながらにDraper gemでActiveRecord Associationをdecorateします。

ほんと少しでも迷ったらまず、ドキュメントちゃんと読むべきだった恥ずかしい。。。

TL;DR

Draper::CollectionDecorator使いましょう

今までやっていたような事

article modelにkaminari gemでpagenationを加え、titleをCapitalizeするdecorateしてみる例

# article_decorator.rb
class ArticleDecorator < Draper::Decorator
  delegate_all

  def title
    object.title.capitalize
  end
end

そんでもって

# controller
@articles = Article.all.page page[:page]

# hamlとかでview
@articles.each do |article|
   - article.decorate
   = article.title

みたいなことやってた。collection回す中でわざわざdecorateしてた。

はずかしい。

associationにはDraper::CollectionDecoratorを使おう

association用のdecoratorを作る

# articles_decorator.rb
class ArticlesDecorator < Draper::CollectionDecorator
  delegate :current_page, :total_pages, :limit_value
end

これで各々のactiveReocrd modelもそれぞれdecorateされます。

あぁ恥ずかしい。。。

参考

6
6
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
6