【问题标题】:Designing models with Ruby On Rails使用 Ruby On Rails 设计模型
【发布时间】:2016-10-20 02:35:58
【问题描述】:
我有以下型号:
要求:
- 一个教室可以有很多课程。一门课程可以属于多个教室。
- 一个教室可以有很多学生。一个学生可以属于多个教室。
- 一个学生可以参加许多课程。一门课程可以属于许多学生。
- 一个学院有很多学生、很多教室和很多课程。
我正在尝试为上述创建关联:
以下是准确的吗?
-
学院: has_and_belongs_to_many :students | has_many :教室 | has_many :课程
-
学生: has_and_belongs_to_many :institutes | has_and_belongs_to_many :教室 | has_many :课程 |属于_to:研究所
-
课堂: has_and_belongs_to_many :students | has_many :课程 |属于_to:研究所
-
课程: has_and_belongs_to_many :students | has_many :教室 |属于_to:研究所
如何在这里使用“通过”关系?
【问题讨论】:
标签:
ruby-on-rails
activerecord
【解决方案1】:
对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