I have two tables:
Users
and Groups
a User has_many groups and a group, has_many a users:
u = User.last
u.groups
g = Group.last
g.users
Supposed I wanted a second list of different groups, for some strange reason. Where once again a User has may groups (called other_group in this example) and a group has many users.
u = User.last
u.other_groups
g = Group.last
g.other_users
How do I associate two models in this relationship, twice using Active Record? Do I need multiple has and belongs to many tables? perhaps a has and belongs to many "through". What does this look like?
Answer:
class Matter < ActiveRecord::Base
has_many :matters_lawfirms
has_many :matters_other_lawfirms
has_many :lawfirms, class_name: 'Lawfirm', through: :matters_lawfirms, :source => :lawfirm
has_many :other_lawfirms, class_name: 'Lawfirm', through: :matters_other_lawfirms, :source => :lawfirm
end
class Lawfirm < ActiveRecord::Base
has_many :matters_lawfirms
has_many :matters_other_lawfirms
has_many :matters, class_name: 'Matter', through: :matters_lawfirms, :source => :matter
has_many :other_matters, class_name: 'Matter', through: :matters_other_lawfirms, :source => :matter
end
class MattersLawfirm < ActiveRecord::Base
belongs_to :matter
belongs_to :lawfirm
end
class MattersOtherLawfirm < ActiveRecord::Base
belongs_to :matter
belongs_to :lawfirm
end
migrations:
class AddMatterOtherLawfirms < ActiveRecord::Migration
def change
create_table :matters_other_lawfirms, :id => false do |t|
t.references :matter, :lawfirm
end
add_index :matters_other_lawfirms, [:matter_id, :lawfirm_id],
name: "matters_other_lawfirms_index",
unique: true
end
end
class AddMatterLawfirmsHabtmt < ActiveRecord::Migration
def change
create_table :matters_lawfirms, :id => false do |t|
t.references :matter, :lawfirm
end
add_index :matters_lawfirms, [:matter_id, :lawfirm_id],
name: "matters_lawfirms_index",
unique: true
end
end