0

I want a method within

class User < ActiveRecord::Base
  def global_user_id
    User.find_by_username("Global_User").id
  end
end

which returns the current global user ID. I want it to be run using User.global_user_id rather than something like User.new.global_user_id

How would I do this?

I'm needing the user ID in other models and right now its stuck in class resources which I dont think is the best spot.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Tallboy
  • 12,847
  • 13
  • 82
  • 173

1 Answers1

4

The key is the self. in the name, it means that this function is a static one tied to the class and not to an instance of it.

class User < ActiveRecord::Base
  def self.global_user_id
    find_by_username("Global_User").id
  end
end
Matzi
  • 13,770
  • 4
  • 33
  • 50
  • Thanks! All comes back to me now... as a sidenote I thought I could do def global_user_id < self, or < User, but those dont seem to work. is this a special case or something? – Tallboy May 27 '12 at 20:16
  • In which case you don't need `User.` in the method call either, since you're already in the correct scope. – Andrew Marshall May 27 '12 at 20:19
  • 1
    @Tallboy Methods can't "inherit" from a class, which is what it looks like you're trying to do there. You can do `class << self; def global_user_id; ... end; end` though. See [`class << self` idiom](http://stackoverflow.com/q/2505067/211563). – Andrew Marshall May 27 '12 at 20:25