简体   繁体   中英

Object with more than one Model (Rails)

BACKGROUND: I'm thinking conceptually about how to reference a single object that can belong to more than one model. For instance, if I have a School and Employer model - a User could theoretically have attended and be employed at the same School. Ideally both relationships to point to the same object.

QUESTION: How would I model that in a postgresql-based Rails app?

UPDATE In this case, I'd need a user to be able to have both one or more Schools and one or more Employers.

EDIT: To reflect that the question was about HABTM

You'd use something like this if you want to be able to use the same exact record for both Employer and School in User.employer . I'm assuming a User can only have one School and one Employer, no more.

class School < ActiveRecord::Base
    has_many :employees, as: :employable
    has_and_belongs_to_many :students, class_name: "User"
end

class Business < ActiveRecord::Base
    has_many :employees, as: :employable
end

class Contract < ActiveRecord::Base #This object models the relationship between User and Employer
    belongs_to :employer, as: :employable, polymorphic: true
    belongs_to :user


class User < ActiveRecord::Base
    has_and_belongs_to_many :schools
    has_many :contracts
    has_many :employers, through: :contracts
end

this would set it up so that if you call User.school it would return a School object, but if you call User.employer it could go to either School or Employer depending on what User points to.

This makes use of Polymorphic Associations . Please read about them as the Migrations are different for this kind of association.

The reason we're using a Contract object is that a has_and_belongs_to_many association can't be polymorphic, so we to roll that out manually. If you don't like has_and_belongs_to_many or need more flexibility for the School relationship, you could use an intermediary object like for employer, maybe called Tuition .

To do this you would have three models, User, School and Employer.

The User belongs_to one School and belongs_to one Employer. The School has_many Users. The Employer has_many Users.

Knowing these relations, which are used directly in your models, you now know that the User will have a school_id and an employer_id attribute. Neither the School nor the Employer will have a user_id .

If you decide to go down the route of users having and belonging to many Schools or Employers ( has_and_belongs_to_many ) then you will want to look at the ActiveRecord documentation on join tables.

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