why use self. for a method ?

hi all. I had a problem with a methods and classes what i had for example was this:

the controller: class AnimalsController < ApplicationController   def index     @id =Animal.item    end end

the model: class Animal   def item     return 2   end end

this doesn't work because you have to maken from the Item Method a Class Method. you do this by doing def self.item.

But why ? and if you have mutiple methods in it you will have to set them all to self. ??

jeljer

What is the difference between a "method" inside the class ModelName < ActiveRecord::Base and a "class model" inside the same model* beside having to use "self." to make it work?

*the model is a class isn't it?

Correction: I want to know the difference between a "method" and a "class method" inside a model (which is a class, isn't it?)

Correction: I want to know the difference between a "method" and a "class method" inside a model (which is a class, isn't it?)

When you have an instance method, you need an instance of the object.
For example if I have a Person class, and Person has a last_name
attribute it makes no sense to say Person.last_name, the class itself
doesn't have a last name, only instances of Person do. If bob is an
instance of Person, then you can say bob.last_name and that makes
perfect sense. With a class method you don't need an instance of the class. For
example if Person is an ActiveRecord class then you have a class
method called find, so you can say Person.find (and writing bob.find
would be a bit weird).

The self. notation is because a class method is actually a singleton
method on the Class. All of your classes are instances of Class,
things like find and so on are singleton methods on those instances of
class. Equvalently you can write

class Foo    class << self     def a_class_method     end

    def another_one     end    end end

Fred