0

I have two existing Models - Schools and Users.

class School < ActiveRecord::Base
has_and_belongs_to_many :users

class User < ActiveRecord::Base
has_and_belongs_to_many :schools

My question is, how can I assign and user to a school? I can't quite figure out how to get it so that School.users returns any values.

2 Answers2

1

The relation is defined for an instance of school (a specific school), so School.users will never work.

Assuming you have the correct tables setup (you will have to manually create the migration for the join table, see for example here), it is actually pretty easy.

school = School.first
user = User.first

# add user to school
school.users << user

# or v.v.
user.schools << school
Community
  • 1
  • 1
nathanvda
  • 49,707
  • 13
  • 117
  • 139
0

If you want a user just to belong to one particular school (which makes most sense in case of students and teachers, staff etc) you need to change your associations to:

School

has_many :users

User

belongs_to :school

Then you also need to have a user_id:integer column in your school table.

Now you can query.

school = School.first

school.users

If you want a many to many relationship you need to create a schools_users table with school_id and user_id field.

Nikolai Manek
  • 980
  • 6
  • 16