Albin
Albin

Reputation: 3032

Find out what foreign key is used in has_many

I am trying to write a gem that can include an automatic count for how many instances there is through a has_many relationship in a single sql query.

I would like the declaration to look like this

class Foo < ActiveRecord::Base
  has_many :bars, foreign_key: :foo_id
  can_count :bars
end

In order for me to make this work I would need a method like Foo.bars_foreign_key or something that would return :foo_id. Is this possible to achieve? Or should I go with the more simplistic approach and assume default foreign key and take custom foreign key as input?

Upvotes: 0

Views: 45

Answers (1)

shivam
shivam

Reputation: 16506

You can use reflections:

Foo.reflections[:bars].foreign_key.to_sym
# => :foo_id

Or something like this for all reflections:

ref_hash = {}
Foo.reflect_on_all_associations.each { |h| ref_hash[h.name] = h.foreign_key }
ref_hash
# => {:bar=>"foo_id", ...}

Upvotes: 2

Related Questions