Gal Bar-or wrote:> Sorry in advance if this is on the wrong forum/topic.
>
> I''m a novice ruby developer, starting to use ActiveRecord, and am
> getting stuck with the following problem:
>
> I have a class defined:
>
> class User < ActiveRecord::Base
> set_table_name "users"
> has_one :locations
> has_one :sessions
> has_many :task_postings
> has_many :task_descriptions
>
>
> def get_messages(uid)
> user = User.find(:first, :conditions => [ "id =
''#{uid}''" ])
> if(user) then
> return user.messages_waiting
> end
> return nil
> end
> end
>
> In order to call the method, I have to create an instance of the class
> and refer to the method:
>
> new_user = User.new
> new_user.get_messages(1)
>
> If I call the method by referring to the class, User.get_messages, I get
> a non-existent method error. What I wanted is to be able to call the
> class as follows:
>
> User.get_messages(1)
>
> in order to do that, I re-defined the class as:
>
> def self.get_messages(uid)
No, actually you don''t want to do this. get_messages is conceptually a
property of an individual user, not of the User class.
You also don''t need uid as an argument, since the User object
you''re
calling this on already knows its id. The proper way to do this would
be
def get_messages # note: no arguments
self.messages_waiting
end
Finally, get_* is somewhat unidiomatic in Ruby; this method should
perhaps just be called messages.
Best,
--
Marnen Laibow-Koser
http://www.marnen.org
marnen-sbuyVjPbboAdnm+yROfE0A@public.gmane.org
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.