Here are my models:
Team:
class Team < ActiveRecord::Base
has_many :team_users
has_many :users, through: :team_users
has_many :admins, through: :team_users,
foreign_key: :user_id,
class_name: 'User',
source: :user,
conditions: ["team_users.is_admin = ?", true]
end
User:
class User < ActiveRecord::Base
has_many :team_users
has_many :teams, through: :team_users
has_many :administered_teams, through: :team_users,
foreign_key: :user_id,
class_name: 'Team',
source: :team,
conditions: ["team_users.is_admin = ?", true]
end
TeamUser:
# == Schema Information
#
# Table name: team_users
#
# id :integer not null, primary key
# team_id :integer
# user_id :integer
# is_admin :boolean
#
class TeamUser < ActiveRecord::Base
belongs_to :team
belongs_to :user
# Validations
validates_presence_of :team
validates_presence_of :user
attr_accessible :is_admin
end
So essentially team.users
and team.admins
are joined through the same table. Note that to be a team.admin
you must be a team.user
.
My question is, how do I save is_admin
in the joiner-model automatically when I append to team.admins
? i.e:
irb(main):001:0> user = User.find(1)
irb(main):002:0> team = Team.create
irb(main):003:0> team.admins << user
irb(main):004:0> team.users.count
=> 1
irb(main):005:0> team.admins.count
=> 0
irb(main):007:0> y team.team_users
- !ruby/object:TeamUser
attributes:
id: 307
team_id: 210
user_id: 1
is_admin:
=> nil
I remember vaguely seeing somewhere that has_many conditions are automatically set. But I'm not sure if this is the case for joiner models? Or perhaps I'm doing it wrong and there is a better implementation?
Update
This question seems very similar to this one.