模型中的多个级别的have_many
我正在使用 Ruby on Rails(特别是 ActiveRecord),并且我正在尝试确定使用多个级别链接我的模型是否是一个好主意。
class Student < ActiveRecord::Base
has_many :student_sections
has_many :sections, :through => :student_sections
has_many :courses, :through => :sections
end
看起来这可行,但我在 ActiveRecord 方面没有很多经验。有什么理由不这样做呢?
I am working with Ruby on Rails (specifically the ActiveRecord) and I am trying to decide whether or not it is a good idea to link my models using multiple levels.
class Student < ActiveRecord::Base
has_many :student_sections
has_many :sections, :through => :student_sections
has_many :courses, :through => :sections
end
It seems like this would work, but I don't have a lot of experience in ActiveRecord. Is there any reason not to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这很好,但您应该记住,课程关联实际上只是一个“获取”关联(而不是“获取和设置”)。我的意思是,你可以说
@student.courses
(在完成neo的修复之后)来获取课程列表,但你不能做
@student.courses << @course
as Rails 没有在学生和课程之间进行必要连接所需的部分信息。
This is fine but you should bear in mind that the courses association is effectively only a 'get' association (as opposed to 'get and set'). What i mean by that is that you can say
@student.courses
(after doing neo's fix) to get a list of courses, but you can't do
@student.courses << @course
as rails doesn't have the section info required to make the necessary joins between the student and the course.
您需要添加 :source 属性
you need to add :source attribute