找出has_many中使用的外键

时间:2015-04-21 13:03:07

标签: ruby-on-rails ruby activerecord

我正在尝试编写一个gem,它可以在单个sql查询中通过has_many关系自动计算有多少个实例。

我希望声明看起来像这样

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

为了让我完成这项工作,我需要一个像Foo.bars_foreign_key这样的方法或者会返回:foo_id的方法。这有可能实现吗?或者我应该采用更简单的方法并假设默认外键并将自定义外键作为输入?

1 个答案:

答案 0 :(得分:2)

您可以使用reflections

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

或类似的所有反思:

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