rails_antipatternsについて書いていきます

1 class UsersController < ApplicationController
2   def index
3     @user = User.find(params[:id])
4     @memberships = @user.memberships.where(:active => true).
5                                      limit(5).
6                                      order("last_active_on DESC")
7   end
8 end

Solution: Push All find() Calls into Finders on the Modelを適用してみよう

[try1] Solution: Push All find() Calls into Finders on the Model

1 class UsersController < ApplicationController
2   def index
3     @user = User.find(params[:id])
4     @recent_active_memberships = @user.find_recent_active_memberships
5   end
6 end
1 class User < ActiveRecord::Base
2   has_many :memberships
3 
4   def find_recent_active_memberships
5     memberships.where(:active => true).
6                 limit(5).
7                 order("last_active_on DESC")
8   end
9 end

AntiPattern

UserModelでMembershipModelのfinderを記述すべきでない。 自身のModelのドメインを明確に。

[try2] move Membership Model finder into the Membership Model From the User Model

1 class User < ActiveRecord::Base
2   has_many:memberships
3 
4   def find_recent_active_memberships
5     memberships.find_recently_active
6   end
7 end
1 class Membership < ActiveRecord::Base
2   belongs_to :user
3 
4   def self.find_recently_active
5     where(:active => true).limit(5).order("last_active_on DESC")
6   end
7 end

where(:active => true)とかorder("last_active_on DESC")のクエリメソッドは他でも結構使えそう

[try3] use the named scope of rails

1 class User < ActiveRecord::Base
2   has_many :memberships
3 
4   def find_recent_active_memberships
5     memberships.only_active.order_by_activity.limit(5)
6   end
7 end
1 class Membership < ActiveRecord::Base
2   belongs_to :user
3   scope :only_active, where(:active => true)
4   scope :order_by_activity, order('last_active_on DESC')
5 end

すっきりー




comments powered by Disqus


© 2015 kyuden