使用Ruby On Rails设计模型

时间:2016-06-18 09:27:44

标签: ruby-on-rails activerecord

我有以下型号:

  • 研究所
  • 学生
  • 教室

要求:

  1. 教室可以有很多课程。课程可以属于许多课堂。
  2. 教室里可以有很多学生。学生可以属于许多教室。
  3. 学生可以参加很多课程。一门课程可以属于很多学生。
  4. 学院有很多学生,很多教室和很多课程。
  5. 我正在尝试为上面创建关联: 以下是准确的吗?

    1. 学院: has_and_belongs_to_many:学生| has_many:教室| has_many:courses
    2. 学生: has_and_belongs_to_many:机构| has_and_belongs_to_many:教室| has_many:课程| belongs_to:institute
    3. 课堂: has_and_belongs_to_many:学生| has_many:课程| belongs_to:institute
    4. 课程: has_and_belongs_to_many:学生| has_many:教室| belongs_to:institute
    5. 我如何在这里使用“通过”关系?

1 个答案:

答案 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