Reputation: 55
I have two models, project and users and I want to connect them as follows:
class Project < ApplicationRecord
belongs_to :owner, class_name: "User"
has_many :members, class_name: "User"
end
class User < ApplicationRecord
has_many :projects
end
Migration looks like this.
class AddReferencesToProject < ActiveRecord::Migration[5.2]
def change
add_reference :projects, :owner
add_foreign_key :projects, :users, column: :owner_id, primary_key: :id
end
end
I did this migration for members_id but I want it to have more then one user_id:
class AddMembersReferencesToProject < ActiveRecord::Migration[5.2]
def change
add_reference :projects, :members
add_foreign_key :projects, :users, column: :members_id, primary_key: :id
end
end
Do I need to make a many_to many :through association? I´m stuck on this.
Upvotes: 0
Views: 1009
Reputation: 20253
Yes, has_many :through
makes sense for your many-to-many association. (I don't tend to use has_and_belongs_to_many
, but that's mostly a personal preference.)
It might look something like:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ApplicationRecord
has_many :owned_projects, class_name: "Project", foreign_key: :owner_id
has_many :project_members, foreign_key: :member_id
has_many :projects, through: :project_members
end
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# owner_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Project < ApplicationRecord
belongs_to :owner, class_name: "User"
has_many :project_members
has_many :members, through: :project_members
end
# == Schema Information
#
# Table name: project_members
#
# id :integer not null, primary key
# member_id :integer
# project_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class ProjectMembers < ApplicationRecord
belongs_to :member, class_name: "User"
belongs_to :project
end
Upvotes: 2