Module: Pluckers::Features::HasAndBelongsToManyReflections

Includes:
Base::HasAndBelongsToManyReflections
Included in:
Base
Defined in:
lib/pluckers/features/active_record_3_2/has_and_belongs_to_many_reflections.rb,
lib/pluckers/features/active_record_4_0/has_and_belongs_to_many_reflections.rb,
lib/pluckers/features/active_record_4_1/has_and_belongs_to_many_reflections.rb,
lib/pluckers/features/active_record_4_2/has_and_belongs_to_many_reflections.rb,
lib/pluckers/features/active_record_5_0/has_and_belongs_to_many_reflections.rb,
lib/pluckers/features/active_record_5_1/has_and_belongs_to_many_reflections.rb

Instance Method Summary collapse

Methods included from Base::HasAndBelongsToManyReflections

#build_results, #configure_query

Instance Method Details

#active_record_has_and_belongs_to_many_reflection?(reflection) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
10
# File 'lib/pluckers/features/active_record_3_2/has_and_belongs_to_many_reflections.rb', line 7

def active_record_has_and_belongs_to_many_reflection? reflection
  reflection.is_a?(ActiveRecord::Reflection::AssociationReflection) &&
  (reflection.macro == :has_and_belongs_to_many)
end

#has_and_belongs_to_many_ids(klass_reflection) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pluckers/features/active_record_3_2/has_and_belongs_to_many_reflections.rb', line 12

def has_and_belongs_to_many_ids klass_reflection

  # First,  we get the the join table
  join_table = Arel::Table.new(klass_reflection.options[:join_table])

  # And now, the foreign_keys.
  # In our example with BlogPost and Category they would be:
  # model_foreign_key = blog_post_id
  # related_model_foreign_key = category_id
  model_foreign_key = klass_reflection.foreign_key
  related_model_foreign_key = klass_reflection.association_foreign_key

  # Now we query the join table so we get the two ids
  ids_query = join_table.where(
      join_table[model_foreign_key].in(@results.map{|_, r| r[:id] })
    ).project(
      join_table[related_model_foreign_key],
      join_table[model_foreign_key]
    )

  join_results = ActiveRecord::Base.connection.execute(ids_query.to_sql)

end