Has_many through association


#1

1))))) class Group < ActiveRecord::Base

has_many :group_users
has_many :users, :through => :group_users
end

2)))))))))class User < ActiveRecord::Base
has_many :group_users
has_many :groups, :through => :group_users
end

3))))))class CreateGroupUsers < ActiveRecord::Migration # JOINING
TABLE
def self.up
create_table :group_users do |t|
t.column :group_id, :string
t.column :user_id, :string
t.column :group_admin, :boolean
t.timestamps
end
end

Can anybody please help me how to set the value of group_admin in
GroupUsers ?

I want to do like this :

@group.group_users.group_admin =1 (X- NOT WORKING THOUGH)


#2

@group.group_users.group_admin =1 (X- NOT WORKING THOUGH)

@group.group_users is not a single entity with the group_admin
attribute, it’s a collection of group_users records…

@group.group_users.each do |group_user|
group_user.group_admin = 1
end

would set that attribute for every group_user record, but I don’t think
that is you want to do.

I’d think you want to assign the group_admin for a single group_users
record for the group, which you’ll need to select according to the
user_id.

A particularly ugly, but very clear implementation, might be:

@group.group_users.each do |group_user|
if group_user.user_id == the_user_id_of_your_admin
group_user.group_admin = 1
end
end


#3

Intern ruby wrote:

Can anybody please help me how to set the value of group_admin in
GroupUsers ?

I want to do like this :

@group.group_users.group_admin =1 (X- NOT WORKING THOUGH)

@group.group_users contains an array of users… so you need to specify
what user to set group_admin=1

try to open script/console and do:

test = Group.find(1)
test.group_users
test.group_users[0]
test.group_users[0].group_admin=1

===============================================================================
Tomas Meinlschmidt, MS {MCT, MCP+I, MCSE, AER}, NetApp Filer/NetCache

www.meinlschmidt.com www.maxwellrender.cz www.lightgems.cz


#4

thanks Chron and Tom. It worked.