ActiveRecord Association Without Foreign Key

I am trying to build a model of user relationships. A user can either initiate a relationship or receive a relationship from another user. Therefore, the relationship table in db has the foreign keys "initiator_id" and "recipient_id".
Now I can understand what kind of relationship the user initiated or received using the following associations:

has_many :initiated_relations, :foreign_key => :initiator_id, :class_name => 'Relation', :dependent => :destroy
has_many :received_relations,  :foreign_key => :recipient_id, :class_name => 'Relation', :dependent => :destroy

What I'm trying to do is create an association that will bring me all the relationships that belong to the user (either initiated or received). Trying to do the following does not work and complains about the absence of the user_id field:

has_many :relations, :conditions => 'recipient_id = #{id} or initiator_id = #{id}'

How to create an association based solely on a condition field without a default foreign_key search? Or maybe a completely different approach to solving this?

+3
source share
2 answers

Well, I can think of using finder_sqlfor this:

has_many :relations, :finder_sql => 'select * from relations right outer join users
    on relations.recipient_id = #{id} or relations.initiator_id = #{id}'

Alternatively, you can simply write a method that returns a combined array of two relationship associations', but you lose the advantage of the association interface (phew).

Perhaps someone will come up with a better solution.

+5
source

@neutrino , "" . Rails 3, , . where() ActiveRecord::Relation, . , , :

def User < ActiveRecord::Base
  def all_relations
    Relation.where("initiator_id => ? OR recipient_id = ?", id, id)
  end
end

:

User.all_relations.where(:confirmed => true).all
+8

Source: https://habr.com/ru/post/1771262/


All Articles