简体   繁体   中英

Rails associations, has_one to has_many

In my app I have 2 classes. User and Classroom. I use the user class as a student as well.

I'm trying to achieve a result where:

A classroom belongs to a user. A user has many classrooms. A classroom has one student through the user class. A student can be associated to many classrooms.

To try and explain further. I have a classroom and the user is the creator of the classroom. When someone joins they are a student of the classroom and I only want there to be one student and one creator.

I want a student to be attached to lots of different classrooms and I want the classrooms to all belong to one user.

My current code for the two classes looks like this:

class User < ActiveRecord::Base

  has_many :classrooms

end

class Classroom < ActiveRecord::Base

    belongs_to :user

    has_one :student, :class_name => "User"

end

Any advice is much appreciated. Thanks!

I think what you are trying to achieve is:

class User < ActiveRecord::Base
  has_many :classroom_users
  has_many :classrooms, through: :classroom_users
end

class ClassroomUser < ActiveRecord::Base
  belongs_to :classroom
  belongs_to :user
end

class Classroom < ActiveRecord::Base
  has_many :classroom_users
  has_many :users, through: :classroom_users
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM