Access to association in a class method

1 view
Skip to first unread message

Maher Hawash

unread,
Nov 5, 2009, 5:30:13 PM11/5/09
to pdx...@googlegroups.com
#
class User
has_many :widgets
end

# In controller, I want to do this, but a widget has not been created.
current_user.widgets.dosomething

#
class Widget
belongs_to :user

def self.dosomething
# I would like to have access to the user_id just like
Widget.new, and Widget.create do

end
end

I would appreciate some insight.

Thanks,

Brent Miller

unread,
Nov 5, 2009, 5:40:57 PM11/5/09
to pdx...@googlegroups.com
You can extend associations with custom behavior:

class User
has_many :widgets do
def dosomething
proxy_target.collect(&:id)
end
end
end

u = User.new
u.widgets.dosomething # => []

In dosomething, you have access to proxy_owner (u) and proxy_target
(the collection of widgets). There's some good documentation about
this in the rails docs: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods

Brent
=======================================================
Brent Miller
http://www.foliosus.com/

"The problem is that once you have done away with the
ability to make judgments as to right and wrong, true
and false, etc., there's no real culture left. All
that remains is clog dancing and macrame."
-- Neal Stephenson
=======================================================

Maher Hawash

unread,
Nov 6, 2009, 9:58:50 AM11/6/09
to pdx...@googlegroups.com
Brent, thank you. That works but now I have my Widget methods in
multiple places. I would have liked
to keep it all in the same file if possible. Is there another way to do this?

Maher

Brent Miller

unread,
Nov 6, 2009, 10:34:23 AM11/6/09
to pdx...@googlegroups.com
You can put those methods in a module:

module WidgetBehavior
def dosomething
...
end
end

class User
has_many :widgets, :extend => WidgetBehavior
end

With code like this, you get:

u = User.new
u.widgets.dosomething

You can also do this, if you want the same behavior on the Widget
class directly:

class Widget
extend WidgetBehavior
end

Widget.dosomething

This last bit won't give you the behavior on the association, however.
It's an optional add-on to the has_many :extend code.

It doesn't save you from having widget-related code in two places, but
at least the two places are reasonably named. Having widget code in
the User model makes me cringe just a little. :)
=======================================================
Brent Miller
Owner and Principal
Foliosus Web Design LLC
http://foliosus.com/

Maher Hawash

unread,
Nov 6, 2009, 10:35:57 AM11/6/09
to pdx...@googlegroups.com
I like this better, thank you.
Reply all
Reply to author
Forward
0 new messages