Reputation: 13378
Using Rails 3.2.17. I have the following in my model:
class Shop < ActiveRecord::Base
before_create :set_next_position
private
def set_next_position
self.position = self.class.where(country_id: country_id).
maximum(:position).to_i + 1
end
end
self
is a Shop
object. Note the line self.class.where...
which is equivalent to Shop.where...
. In this case, I don't know what is the best practice - to use Shop.where...
or self.class.where...
? It is code smell to me.
Upvotes: 0
Views: 60
Reputation: 3984
I would say self.class.where
is better than Shop.where
inside the class body. This way, you won't have to change inside, if for some reason you want to rename the class and so on.
Upvotes: 1
Reputation: 311
The only difference that I now about is in case of inheritance. When you have:
class Base
def self.example
42
end
def run_example
Base.example
end
end
class A < Base
def self.example
'not 42'
end
end
A.new.run_example
=> 42
So when don't have inheritance I prefer Base.example
. In the other case self.class.example
.
Upvotes: 0