2015-09-25 122 views
0

考虑到以下模型,我怎样才能选择用户拥有的学生笔记?另外,模型看起来好吗?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 

在此先感谢!

+0

提醒你的关系了像图。这可以帮助我很多 – snowYetis

+0

snowyetis说了些什么。我的问题是为什么你要创建一个单独的用户和学生表?无论如何,如果你想从用户的学生那里拿回所有的笔记,你将不得不以迂回的方式来完成。当你调用User.students时,你将获得一个ActiveRecord关系(它基本上是与你的用户相关的所有学生对象的一个​​数组)。你必须建立另一个数组,迭代每个学生然后找回他们的笔记列表,并将他们的笔记对象推送到这个新的数组中。 –

+1

另一个问题 - 关系表是什么? –

回答

0

你可以简化你的模型切断StudentNoteRelationship和使用has_and_belongs_to_many协会代替。

只选择用户所拥有的学生的笔记,你可以添加has_many :notes, :through => :studentsUser模型

你的模型应该是这样的:

class Student < ActiveRecord::Base 
    has_and_belongs_to_many :notes 
    has_and_belongs_to_many :users 
end 

class Note < ActiveRecord::Base 
    has_and_belongs_to_many :students 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :students 
    has_many :notes, :through => :students 
end 

而且你可以选择学生的笔记用户拥有这样:

some_user.notes

+0

感谢您的回答。就像上面解释的那样,Relationship和StudentNote模型可能会有更多的属性,比如'status'和'kinship'。 – Luis

0

您可以简单地添加notes关系:

class User < ActiveRecord::Base 
    has_many :relationships 
    has_many :students, :through => :relationships 

    # new relation 
    has_many :notes, :through => :students 
end 

和查询:

my_user.notes 
+0

谢谢你的回答! – Luis