I am trying to create the following basic structure with RoR. The key is that all Users also be linked to a School and a Major. Users will write articles based on their School and Major. The linking is not exclusive: many users can be in one of many schools, and one of many majors. However, each user cannot be in more than one school, and cannot be in more than one major. Eventually, I would like to be able to show posts/filter articles based on the following:
- All Users in both Major X and at School Y
- All Majors at School Y
- All Schools with Major X
I've done a little research, not sure if any of this is correct... (still learning) should I be using has_and_belongs_to_many below as compared to has_many?
Table
major_schools #(linking the two models below)
Models
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
What I need to do is also incorporate a user model with the two above:
class User < ActiveRecord::Base
has_and_belongs_to_many :major_schools
end
And I am quite stuck... How can I pull in the User model data to the above models?