I know that self
is the instance inside of an instance method. So, then, is self
the class inside of a class method? E.g., Will the following work in Rails?
class Post < ActiveRecord::Base
def self.cool_post
self.find_by_name("cool")
end
end
That is correct. self
inside a class method is the class itself. (And also inside the class definition, such as the self
in def self.coolpost
.)
You can easily test these tidbits with irb:
class Foo
def self.bar
puts self.inspect
end
end
Foo.bar # => Foo
class Test
def self.who_is_self
p self
end
end
Test.who_is_self
output:
Test
Now if you want a Rails specific solution, it's called named_scopes:
class Post < ActiveRecord::Base
named_scope :cool, :conditions => { :name => 'cool' }
end
Used like this:
Post.cool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With