Aaquib Khan Aaquib Khan - 1 year ago 93
Ruby Question

Creating a new table in mongoid for has_and_belongs_to_many relationship

I just started to code in rails using mongoid ,previously I coded in sql,sqlite etc,Now Iam a bit confused between associations.like in sql when you want a has_and_belongs_to_many association between two models you do in such a way

for example

class Student < ActiveRecord::Base
has_and_belongs_to_many :subjects
end

class Subject < ActiveRecord::Base
has_and_belongs_to_many :students
end


and we create a new table as

rails g migration CreateJoinTableStudentSubject student subject


In our migration file we do like this

def change
create_table :students_subjects do |t|
t.references :student
t.references :subject
t.timestamps
end


end

now my question is is this neccesary to create a new table when using mongoid or der is a alternative way for doing this.plz help Iam new to mongoid and rails.thank you

Answer Source

You just need to include some code into your classes like this:

class Student
  include Mongoid::Document
  has_and_belongs_to_many :subjects
end

class Subject
  include Mongoid::Document
  has_and_belongs_to_many :students
end

There is a great documentation here.

Hope it will help you!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download