简体   繁体   中英

Rails - model belongs_to and has_one same class

I have two models, User and Request

By definition, A User can have many requests, and each Request has one assigned agent (who can be a different user)

with the base as,

class User < ActiveRecord::Base
   has_many :requests
end

But there's a column in Request model, agent_id which has to be linked to User. So how do I set the relationships the best way for,

1. User has_many requests (with column requests.user_id) 
2. Request has_one user(with column requests.agent_id)

Both these on Requests table

This may be what you're looking for.

class User < ActiveRecord::Base
   has_many :requests
end

class Request < ActiveRecord::Base
   belongs_to :user
   belongs_to :agent, class_name: 'User', foreign_key: 'agent_id'
end

You'd use the long form version of the associations. Look them up in the source code to see all the options, but for this example only one extra option needs to be specified since everything else is default.

For user

has_many :requests, foreign key: :agent_id

For request

has_one :user, foreign_key: :agent_id

It should works

class User < ActiveRecord::Base
   has_many :requests
end

class Request < ActiveRecord::Base
   belongs_to :agent, class_name: 'User'
end

If you want also link User with agent_id :

class User < ActiveRecord::Base
   has_many :requests, foreign_key: 'agent_id'
end

The best way to establish Relationships is to follow Rails Naming Conventions. Rename column 'agent_id' to 'user_id'.

By doing so, you can use

class User < ActiveRecord::Base
   has_many :requests
end

class Request < ActiveRecord::Base
   belongs_to :user
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