【问题标题】:Rails - model relationship suggestionRails - 模型关系建议
【发布时间】:2018-10-27 11:00:21
【问题描述】:

是否可以定义如下关系:

  1. “学生”属于“组”
  2. 一个“小组”有很多“课程”和很多“学生”
  3. “学生”通过其所属的“组”拥有许多“课程”

我知道如何使用另外一张表(添加一个包含学生 ID 及其所属课程的 student_course 表,然后说该学生 has_many :courses, through: :student_course)。

也就是说,可以通过编辑下表来实现吗?

class Student
  belongs_to :group
end

class Group
  has_many :students
  has_many :courses
end

class Course
  belongs_to :group
end

【问题讨论】:

  • 为了说“多一张桌子”,你需要明确你想到的桌子,你没有说出来。
  • 嘿 Sawa,我刚刚添加了我已经拥有的表格 :)

标签: ruby-on-rails relational-database


【解决方案1】:

试试下面的联想

学生.rb

belongs_to :group
has_many :courses, through: :group

group.rb

has many :courses
has many :students

课程.rb

belongs_to :group
has_many :students, through: :group

【讨论】:

  • @KristiyanTsvetanov 哦,这是错误的,更新了我的答案,感谢您纠正我:)
  • @KristiyanTsvetanov 你试过我的解决方案了吗?
【解决方案2】:

不确定是否可以使用 Rails 类方法来实现,但可以手动实现。

class Student
  belongs_to :group

  def courses
    group.courses
  end
end

class Group
  has_many :students
  has_many :courses
end

class Course
  belongs_to :group
end

【讨论】:

  • 我想我必须再复习一些基本的东西......谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多