through

inverse_of

UPDATE

User

Team

through

UserMembership

class User < ActiveRecord::Base has_many :user_memberships has_many :teams, through: :user_memberships end class Team < ActiveRecord::Base has_many :user_memberships has_many :users, through: :user_memberships end class UserMembership < ActiveRecord::Base belongs_to :team belongs_to :user validates :team, :user, presence: true end

UserMembership

team = Team.new(users: [User.first]) team.valid? #=> true team.user_memberships #=> []

UserMembership

team = Team.new(users: [User.first]) team.valid? #=> false team.user_memberships #=> [# ] team.user_memberships.first.team #=> nil

team

UserMembership

team

validate :team, :user, presence: true

team

inverse_of

class User < ActiveRecord::Base has_many :user_memberships, :inverse_of => :user has_many :teams, through: :user_memberships end class Team < ActiveRecord::Base has_many :user_memberships, :inverse_of => :team has_many :users, through: :user_memberships end team = Team.new(users: [User.first]) team.valid? #=> true team.user_memberships.first.valid? #=> true team.user_memberships.first.team #=> #

inverse_of

UserMembership

team

inverse_of