Help Adding "class method" to model

I can’t help but think this should be really easy, but I am pulling my
hair out.

I have a model “Task”

class Task < ActiveRecord::Base
acts_as_nested_set

def rootsForUser(user)

end
end

In the controller, I have:
@tasks = Task.rootsForUser(current_user)

I get “NoMethodError in TasksController#index”

Why can’t I find it? (Is this some weird rails-ism where I haven’t
named the method the “correct” thing?)

Thanks in advance,

Alan

First of all, I highly suggest you stop your Rails stuff and learn
Ruby itself:

http://whytheluckystiff.net/ruby/pickaxe/

That said, here’s the short of what you’re doing.

In your code, you’re defining an instance method for Task. Thus t =
Task.new; t.rootsForUser(user) is what you’ve told Ruby you want.

If you want a class method, it’s simply:

class Task < ActiveRecord::Base
acts_as_nested_set

def self.rootsForUser(user)

end
end

The reasons for the “self” are explained in the link above. Please read
it.

Jason R.

Why can’t I find it? (Is this some weird rails-ism where I haven’t
named the method the “correct” thing?)

Thanks in advance,

Alan

Hi Alan,

Does renaming your method to self.rootsForUser(user) help?

Robin

On 10 Apr 2008, at 16:44, Alan S. wrote:

No, renaming it to self.rootsForUser(user) does not help. I get the
same error.

Well you do need to declare it as
def self.rootsForUser(user)

end
that’s just the way ruby works. On top of that there may be something
else wrong (the error message in the log files should say exactly
which method couldn’t be found for example.

Fred

No, renaming it to self.rootsForUser(user) does not help. I get the
same error.

–Alan

I made a mistake. It had gone on to my next problem. Which I now
have resolved. Thanks for your help. I have read the pickaxe book,
but for it to become working knowledge in my head I have to have done
a project, which I am doing now. Perhaps I should have done something
less ambitious, but I am learning a lot. :slight_smile:

Thanks,

Alan

On Thu, Apr 10, 2008 at 10:47 AM, Frederick C.