考虑到以下模型,我怎样才能选择用户拥有的学生笔记?另外,模型看起来好吗?Rails has_many关联
class Student < ActiveRecord::Base
has_many :student_notes
has_many :notes, :through => :student_notes
has_many :relationships
has_many :users, :through => :relationships
end
class Note < ActiveRecord::Base
has_many :student_notes
has_many :students, :through => :student_notes
end
class StudentNote < ActiveRecord::Base
belongs_to :student
belongs_to :note
end
class User < ActiveRecord::Base
has_many :relationships
has_many :students, :through => :relationships
end
class Relationship < ActiveRecord::Base
belongs_to :student
belongs_to :user
end
在此先感谢!
提醒你的关系了像图。这可以帮助我很多 – snowYetis
snowyetis说了些什么。我的问题是为什么你要创建一个单独的用户和学生表?无论如何,如果你想从用户的学生那里拿回所有的笔记,你将不得不以迂回的方式来完成。当你调用User.students时,你将获得一个ActiveRecord关系(它基本上是与你的用户相关的所有学生对象的一个数组)。你必须建立另一个数组,迭代每个学生然后找回他们的笔记列表,并将他们的笔记对象推送到这个新的数组中。 –
另一个问题 - 关系表是什么? –