Class: ActiveRecord::Relation

Inherits:
Object
  • Object
show all
Defined in:
lib/remote_association/active_record/relation.rb

Instance Method Summary collapse

Instance Method Details

#includes_remote(*args) ⇒ Object

Queues loading of relations to ActiveModel models of models, selected by current relation. The full analogy is includes(*args) of ActiveRecord: all the realted objects will be loaded when one or all objects of relation are required.

May raise RemoteAssociation::SettingsNotFoundError if one of args can’t be found among Class.activeresource_relations settings

Would not perform remote request if all associated foreign_keys of belongs_to_remote association are nil

Returns self - ActiveRecord::Relation

Examples

Author.scoped.includes_remote(:profile, :avatar).where(author_name: ‘Tom’).all



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/remote_association/active_record/relation.rb', line 19

def includes_remote(*args)
  args.each do |r|
    settings = klass.activeresource_relations[r.to_sym]
    raise RemoteAssociation::SettingsNotFoundError, "Can't find settings for #{r} association" if settings.blank?

    if settings[:polymorphic]
      puts "Preload of polymorphic associations not supported"
      next
    end

    ar_class = settings[:class_name].constantize

    remote_associations << OpenStruct.new(
                            ar_accessor:      r.to_sym,
                            foreign_key:      settings[:foreign_key],
                            ar_class:         ar_class,
                            association_type: settings[:association_type]
                          )
  end

  self
end

#where_remote(conditions = {}) ⇒ Object

Adds conditions (i.e. http query string parameters) to request of each remote API. Those are parameters to query string.

Returns self - ActiveRecord::Relation

Example

Author.scoped.includes_remote(:profile, :avatar).where_remote(profile: {public: true}, avatar: { primary: true }).all

#=> Will do requests to: # * …/prefiles.json?author_id[]=1&author_id[]=N&search[public][]=true # * …/avatars.json?author_id[]=1&author_id[]=N&primary=true



53
54
55
56
57
58
59
# File 'lib/remote_association/active_record/relation.rb', line 53

def where_remote(conditions = {})
  conditions.each do |association, conditions|
    remote_conditions[association.to_sym] = remote_conditions[association.to_sym].deep_merge(conditions)
  end

  self
end