5
6

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.

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されます。

あぁ恥ずかしい。。。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?