我有以下型号:
要求:
我正在尝试为上面创建关联: 以下是准确的吗?
我如何在这里使用“通过”关系?
答案 0 :(得分:0)
为Classroom
关联和Cource
关联
运行:
ruby homework.rb
#homework.rb
require 'active_record'
`rm foobar.db`
class User < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: 'foobar.db'
connection.create_table table_name, force: true do |t|
t.string :name
end
connection.create_table :institutes_users, id: false do |t|
t.integer :user_id
t.integer :institute_id
end
has_and_belongs_to_many :institutes
end
class Institute < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: 'foobar.db'
connection.create_table table_name, force: true do |t|
t.string :name
end
connection.create_table :institutes_students, id: false do |t|
t.integer :student_id
t.integer :institute_id
end
has_and_belongs_to_many :users
has_and_belongs_to_many :students
has_many :classrooms
has_many :courses
end
class Student < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: 'foobar.db'
connection.create_table table_name, force: true do |t|
t.string :name
end
connection.create_table :classrooms_students, id: false do |t|
t.integer :student_id
t.integer :classroom_id
end
has_and_belongs_to_many :institutes
has_and_belongs_to_many :classrooms
has_many :courses
end
class Classroom < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: 'foobar.db'
connection.create_table table_name, force: true do |t|
t.string :name
t.references :institute
end
belongs_to :institute
has_and_belongs_to_many :students
end
class Course < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: 'foobar.db'
connection.create_table table_name, force: true do |t|
t.string :name
t.references :institute
t.references :student
end
belongs_to :institute
belongs_to :student
end
user = User.create!(name: 'John')
institute = Institute.create!(name: 'Harvard')
student = Student.create(name: 'Mary')
institute.users << user
institute.classrooms.create(name: '4th floor room')
institute.courses.create(name: 'IT')
institute.students << student
student.classrooms << Classroom.create(name: '5th froor room')
student.courses << Course.create(name: 'Biology')
p institute.users
p institute.classrooms
p institute.courses
p institute.students
p student.classrooms
p student.courses