Has_and_belongs_to_many -- has anyone made this easier yet?

Not that this isnt REALLY EASY already… it is!!! I was just wondering
if
someone had already waved their magic wand on this problem. :slight_smile:

I’ve got users and groups… both has_and_belongs_to_many eachother. I
want
to be able to check for the users and groups by ID# or string to make
the
coding easier. So in User, I have this:

has_and_belongs_to_many :groups, :join_table => “users_groups” do
def include?(group)
if group.class == Fixnum
group = Group.find group
elsif group.class == String
group = Group.find_by_name group
end
super
end
end

and in Group, I have this:

has_and_belongs_to_many :users, :join_table => “users_groups” do
def include?(user)
if user.class == Fixnum
user = User.find user
elsif user.class == String
user = User.find_by_name user
end
super
end
end

… is there a way to do it better, more clearly, with less lines of
code?

Thanks,
Tyler

Tyler MacDonald wrote:

Not that this isnt REALLY EASY already… it is!!! I was just wondering if
someone had already waved their magic wand on this problem. :slight_smile:

I’ve got users and groups… both has_and_belongs_to_many eachother. I want
to be able to check for the users and groups by ID# or string to make the
coding easier.

Could you show some unit tests that reveal what this easier coding is
supposed to look like?


Phlip
Redirecting... ← NOT a blog!!!

Phlip [email protected] wrote:

Not that this isnt REALLY EASY already… it is!!! I was just wondering if
someone had already waved their magic wand on this problem. :slight_smile:

I’ve got users and groups… both has_and_belongs_to_many eachother. I want
to be able to check for the users and groups by ID# or string to make the
coding easier.
Could you show some unit tests that reveal what this easier coding is
supposed to look like?

Not a chance. What I was hoping to do was eliminate that “do” block and
have
some magic wand to replace it that recognizes that when I do something
like:

user.groups << “Admin”

or

user.groups << 1

it will just do the right thing.

However, my pride and respect for ruby is brimming right now, so I will
share my modified acts_as_authenticated, which allows you to do:

require_group :Admin

(or any other group name) in a controller, and have login decisions
based
upon that. :slight_smile:

  • Tyler