Reputation: 1680
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
Upvotes: 4
Views: 1131
Reputation: 29174
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
Upvotes: 4
Reputation: 445
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
Upvotes: -1
Reputation: 4615
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
Upvotes: 0
Reputation: 26788
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
Upvotes: 0