我正在尝试使用RoR创建以下基本结构。关键是所有用户也可以链接到学校和专业。用户将根据他们的学校和专业撰写文章。链接并不是唯一的:许多用户可以在众多学校中的一个,也是众多专业中的一个。但是,每个用户不能在一个以上的学校,也不能在一个以上的专业。最后,我希望能够根据以下内容显示帖子/过滤器文章:
我做了一些研究,不确定这是否正确... (仍在学习)我应该在下面使用has_and_belongs_to_many与has_many相比吗?
表
major_schools #(linking the two models below)
模型
class School < ActiveRecord::Base
has_many :major_schools
has_many :majors, :through => :major_schools
end
class Major < ActiveRecord::Base
has_many :major_schools
has_many :schools, :through => major_schools
end
@school.majors #now gives a list of all the majors this school has
@major.schools #still gives a list of all schools that have this major
我需要做的是将用户模型与上述两个结合起来:
class User < ActiveRecord::Base
has_and_belongs_to_many :major_schools
end
我很困惑......如何将用户模型数据引入上述模型?
答案 0 :(得分:1)
你的域名模型在这里纠缠不清,但它确实有用。
以下是一种加载身份ID为X的所有用户和身份为Y的学校的所有用户的方法:
class MajorSchool < ActiveRecord::Base
belongs_to :major
belongs_to :school
has_and_belongs_to_many :users
end
# Load all users from this school/major combination
MajorSchool.where(major_id: X, school_id: Y).users
答案 1 :(得分:1)
为什么不简单地做:
class School < ActiveRecord::Base
has_many :major_schools
has_many :majors, :through => :major_schools
has_many :users
end
class Major < ActiveRecord::Base
has_many :major_schools
has_many :schools, :through => major_schools
has_many :users
end
class User < ActiveRecord::Base
belongs_to :school
belongs_to :major
end
然后你应该能够做到:
# all students of the school
@school.users
# all students of the school and major (each line should return the same results)
@school.users.where(major_id: @major.id)
@major.users.where(school_id: @school.id)
User.where(school_id: @school.id, major_id: @major.id)