My own methods on model + "extends" problem?

Hello.

I have a UsersController and a Model called User with a "new" method,
like this:

class User < ActiveRecord::Base

      def test
           return 1 #I can do anything and return any data, the
problem continues.
      end

end

The problem is that I cannot access my "test" function from the
controller. It says that the method doesn't exists.

class UsersController < ApplicationController

         def index
                  render :text => User.test # Produces the error.
         end

end

Additionally, I cannot access the mehod increase! and other methods of
the ActiveRecord::Base class, that is extended by the User class.
Shouldn't it be accessible?

The User.methods doesn't display the method I created and I cannot
access it. However, other very used methods, like "find" are not shown
by User.methods, but they are accessible.

Anyone can explain me how these things work?

Thank you very much.

Correction: The method is increment! not increase!

It's an issue of Class methods, version Instance methods.

"def test" defines an instance method - @user.test

"def self.test" defines a Class method - User.test

In your example you defined an instance method, and tried to call a Class method (User.test).

cheers,
Jodi

Just to expand a little:

The #find method is defined at http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001005,
but the "find_by..." class of methods is defined dynamically in the
#missing_method method that is part of Ruby and used to good advantage
in Rails. That is why Rails is able to implement such a broad range
of #find_by_* model methods - they are implemented dynamically.

As Jodi says, your case is tripped up because of the difference
between class methods and instance methods.

So if you did the following (note the call to the #new method which
returns an instance of the User object:
         def index
                  render :text => User.new,test
         end

I suspect you would get the right response.

Cheers, --Kip

Thank You both :wink:

... And what about the "increment" method? How to use it?

Thanks again

Ex:

If I use this:

class RomsController < ApplicationController

         def login
               @user = user.find(5)

               @user.increment! "visits"
           end
end

Returns the error "invalid method increment!", but, when I use in the
view <%=@rom.methods %>, it displays the increment! method.

I think I haven't gotten the correct way to send variables to the
view yet.... :frowning:

Thanks again