Hi guys, I have the strangest thing happening. The funny part is its
doing exactly what I want to do, I just don’t understand how.
Basically here is my model.
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
has_and_belongs_to_many :rights
def self.names
names = Array.new()
for role in Role.find :all
names << role.name
end
return names
end
end
migration file for reference:
class CreateRoles < ActiveRecord::Migration
def self.up
create_table :roles_users, :id => false do |t|
t.column “role_id”, :integer
t.column “user_id”, :integer
end
create_table :roles do |t|
t.column "name", :string
end
end
def self.down
drop_table :roles_users
drop_table :roles
end
end
As you can see I wrote a self.names methods so that I can easily call
all the names out of the roles table like so:
role_names = Role.names
=> [“trainers”,“admins”]
So that makes perfect sense.
So the weird but cool part, is that when I go to grab all the names of
the roles that belong to a user like so:
user = User.find :first
=> #<User:0x25cd680 @attributes={“id”=>“1”,
“login”=>“trainer”,“email”=>“[email protected]”}>user.roles
=> [#<Role:0x25c6998 @attributes={“name”=>“trainer”, “role_id”=>“1”,
“id”=>“1”, “user_id”=>“3”}>]user.roles.names
=> [“trainer”]
How does that work?
I aspected it to error out, or even require some sort of special
instance ‘names’ definition at the very least.
So, I’ve been digging and have released that ‘roles’ just calls a
special has_and_belongs_to_many find definition, but I’m still floored
that this works the why I want it to - but just can’t grasp what is
going on. I’m guessing that the Role.find methods I’m calling from
within the self.names method is using a cached copy of all the roles
found earlier by the user.roles methods???
Any suggestions or riddle solving would be greatly appreciated.
Thanks,
Jim