Coding active Coding active - 1 month ago 4
Ruby Question

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

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

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