Forum: Ruby on Rails has_many through association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Intern r. (Guest)
on 2009-05-07 19:49
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)
Ar C. (Guest)
on 2009-05-07 20:46
>
> @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
Tom Z Meinlschmidt (Guest)
on 2009-05-07 20:49
(Received via mailing list)
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
===============================================================================
Intern r. (Guest)
on 2009-05-07 21:32
thanks Chron and Tom. It worked.
This topic is locked and can not be replied to.