【发布时间】:2014-05-03 21:25:17
【问题描述】:
我对 Ruby on Rails 比较陌生。我正在使用 Rails 4.0.4。我有一个表“Schedule”,其中有一列标题为“:course_id”。我想在一个名为“行程”的新表中找到不同课程的所有组合。
因此,如果有一个时间表表,其中包含由 2 个不同课程组成的 3 个部分,则每个组合都是 2 个不同课程的唯一组合。
例如: 附表 1 有:{ section_id: 4, course_id: 1 }, { section_id: 5, course_id: 1 }, { section_id: 6, course_id: 2 }
这将返回 2 个行程:
行程一:{ section_id: 4, course_id: 1 }, { section_id: 6, course_id: 2 }
行程二:{ section_id: 5, course_id: 1 }, { section_id: 6, course_id: 2 }
以下是我的模型及其连接的列表。
时间表:
class Schedule < ActiveRecord::Base
has_many :sections
has_many :courses, through: :sections
has_many :subjects, through: :courses
end
部分:
class Section < ActiveRecord::Base
belongs_to :courses
belongs_to :schedule
end
课程:
class Course < ActiveRecord::Base
belongs_to :subject
belongs_to :schedule
has_many :sections
end
在我的 schedules_controller 中,我有一个方法可以访问从所有可用的不同部分构建的时间表,这就是我努力寻找一个好的方法或方式的地方。我可以遍历每个不同课程的所有部分并手动进行这些组合,但似乎应该有一些更直接的方法来做这样的事情。
def get_itineraries
schedules = Schedule.all
end
【问题讨论】:
-
你能写一个你想要的小例子吗?不是 33 和 6,而是 3 和 2...
-
好的,我编辑了原文,谢谢!
标签: mysql ruby-on-rails