Rails has_many 关联 [英] Rails has_many associations
本文介绍了Rails has_many 关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下模型,如何只选择用户拥有的学生笔记?另外,模型看起来还好吗?
Considering the following models, how can I select only the notes of students owned by a user? Also, do the models look ok?
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
提前致谢!
推荐答案
你可以简化你的模型,去掉 StudentNote
和 Relationship
并使用 has_and_belongs_to_many
代码> 关联.
You could simplify your models cutting off StudentNote
and Relationship
and using the has_and_belongs_to_many
association instead.
要仅选择用户拥有的学生笔记,您可以添加 has_many :notes, :through =>;:students
到您的 User
模型
To select only the notes of students owned by a user, you could add has_many :notes, :through => :students
to your User
model
您的模型应如下所示:
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
您可以通过这种方式选择用户拥有的学生的笔记:
And you could select the notes of students owned by a user this way:
some_user.notes
这篇关于Rails has_many 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文