(Rails Question) Merging multiple hasm polymorphic relationships

(This is not the code I use, although it sums up the idea of ​​what I want to do)

class Connection < ActiveRecord::Base
  belongs_to :connection1, :polymorphic => true
  belongs_to :connection2, :polymorphic => true
end

class User < ActiveRecord::Base
  has_many :followers, :class_name => 'Connection', :as => :connection1
  has_many :followings, :class_name => 'Connection', :as => :connection2
end

My question is that I want to know how I can create a "network" method, so the return is not an array. In this way,

u = User.first
u.network # this will return a merged version of :followings and :followers

So I can still do this:

u.network.find_by_last_name("James")

ETA:

Or hmm, I think my question really comes down to the fact that you can create a method that combines the 2 has_many associations in such a way that I can still call its find_by methods.

+3
source share
1 answer

Are you sure you want to create a Connections collection, not a user collection?

, , , Connection ( , ).

connection.rb

class Connection < ActiveRecord::Base
  class << self
    def associated_with_model_id(model, model_id)
      include([:connection1, :connection2]).
      where("(connection1_type IS #{model} AND connection1_id IS #{model_id})
            OR (connection2_type IS #{model} AND connection2_id IS #{model_id})")
    end
  end
end

user.rb

class User < ActiveRecord::Base
  def network
    Connection.associated_with_model_id(self.class.to_s, id)
  end
end

, , , , , .

0

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


All Articles