D
D
dexdev2015-08-16 18:17:00
Ruby on Rails
dexdev, 2015-08-16 18:17:00

How to properly organize has_many: through links in RoR?

There are companies that can exchange messages, but only after confirming that they wish to exchange messages with other companies.
To do this, I created the Invintation model

class Invintation < ActiveRecord::Base
  belongs_to :company
  belongs_to :recipient, class_name: 'Company', foreign_key: 'recipient_id', primary_key: 'recipient_id'
  belongs_to :author, class_name: 'User', foreign_key: 'author_id'
end

In the Company model I prescribe recipients
class Company < ActiveRecord::Base
  has_many :users_companies
  has_many :users, through: :users_companies
  has_many :messages
  has_many :invintations, class_name: 'Invintation', foreign_key: 'recipient_id'
  has_many :recipients, through: :invintations, class_name: 'Company'
end

but at the request of @company.recipients nothing comes out, I can’t figure out how to bind the same model through througth, please tell me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jeiwan, 2015-08-16
@AdilA

The company can be the sender of the invitation, or it can be the recipient. The invitation stores information about the sender and the recipient (recipient_id and sender_id). A company may have multiple invitations sent and may have multiple invitations from other companies.
Invitation
belongs_to :recipient, class_name: 'Company', foreign_key: 'recipient_id'
belongs_to :sender, class_name: 'Company', foreign_key: 'sender_id'
Company
has_many :sent_invitations, class_name: 'Invitation', foreign_key: 'sender_id' - sent by company has_many : invitation_recipients
, through: :sent_invitations, source: :recipient - invitation recipients
has_many :incoming_invitations, class_name: 'Invitation', foreign_key: 'recipient_id' - invitations received by the company
has_many :invitation_senders, through: :incoming_invitations, source: :sender - invitation senders

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question