Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many through with condition, build new

I've got users and organisations with a join model UsersOrganisation. Users may be admins of Organisations - if so the is_admin boolean is true.

If I set the is_admin boolean by hand in the database, Organisations.admins works as I'd expect.

In the console, I can do Organisation.first.users << User.first and it creates an organisations_users entry as I'd expect.

However if I do Organisation.first.admins << User.last it creates a normal user, not an admin, ie the is_admin boolean on the join table is not set correctly.

Is there a good way of doing this other than creating entries in the join table directly?

class User < ActiveRecord::Base

  has_many :organisations_users
  has_many :organisations, :through => :organisations_users

end

class Organisation <  ActiveRecord::Base

  has_many :organisations_users
  has_many :users, :through => :organisations_users
  has_many :admins, :through => :organisations_users, :class_name => "User", 
            :source => :user, 
            :conditions => {:organisations_users => {:is_admin => true}}

end

class OrganisationsUser < ActiveRecord::Base

  belongs_to :organisation
  belongs_to :user

end
like image 534
Edward Avatar asked Feb 20 '23 08:02

Edward


1 Answers

You can always override the << method of the association:

has_many :admins do

  def <<(user)
    user.is_admin = true
    self << user
  end

end

(Code has not been checked)

like image 52
Erez Rabih Avatar answered Feb 27 '23 16:02

Erez Rabih