Reputation: 710
so i'm working on a rails 4 app and i have two models a Developer and an App.
Basically i want a Developer to act as a founder and have multiple Apps and those apps belong to the Developer (founder). Then i want and app to have many collaborators and a collaborator belongs to many apps. Heres my code, is this right? An how would i lets say add a collaborator to an app?
App
has_and_belongs_to_many :collaborators, class_name: 'Developer', foreign_key: :collaborator_id
has_and_belongs_to_many :founders, class_name: 'Developer', foreign_key: :founder_id
Developer
has_and_belongs_to_many :apps, foreign_key: :collaborator_id
has_and_belongs_to_many :apps, foreign_key: :founder_id
Relations Table
def change
create_table :apps_developers, id: false do |t|
t.references :founder, references: 'Developer'
t.references :collaborator, references: 'Developer'
t.references :app
t.boolean :collaborator_pending, default: :true
end
add_index :apps_developers, [:founder_id, :app_id], unique: true
add_index :apps_developers, [:collaborator_id, :app_id, :collaborator_pending], unique: true, name: 'index_apps_collaborators'
end
Upvotes: 0
Views: 83
Reputation: 29301
You should use HABTM for collaborators and has_many
for founders, not the other way around.
The reason is the relationship between collaborators and apps is many-to-many, while the relationship between founders and apps is one-to-many.
/app/models/app.rb
Class App < ActiveRecord::Base
belongs_to :founder, :class_name => 'Developer'
has_and_belongs_to_many :collaborators, :class_name => 'Developer'
end
/app/models/developer.rb
Class Developer < ActiveRecord::Base
has_many :apps, :foreign_key => :founder_id
has_and_belongs_to_many :apps, :foreign_key => :collaborator_id
end
As for your second question, this is how you can add a collaborator to an app:
app.collaborators << developer
Where app
is an object of the App
class and developer
is an object of the Developer
class.
Upvotes: 1