Get foreign key field from associations in Rails

Dipendra Singh picture Dipendra Singh · Sep 7, 2012 · Viewed 9.4k times · Source

I want to know field name corresponding to table caption for a given model in Rails.

I am displaying captions using a query model.

query.columns.map{|q| q.caption}
=> ["Tracker", "Status", "Priority", "Subject", "Assignee", "Target version", "Due date", "% Done"]

Column has names corresponding to captions

query.columns.map{|q| q.name}
=> [:tracker, :status, :priority, :subject, :assigned_to, :fixed_version, :due_date, :done_ratio]

My model looks like

Issue.columns.map{|q| q.name}
=> ["id", "tracker_id", "project_id", "subject", "description", "due_date", "category_id", "status_id", "assigned_to_id", "priority_id", "fixed_version_id", "author_id", "created_on", "updated_on", "start_date", "done_ratio", "estimated_hours", "parent_id"]

I want to get field name(the db field name) corresponding to a caption from the above information.

Sample association in the model

belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'

So for above association i want to know the foreign key.

for assigned_to i want 'assigned_to_id'

Answer

Frederick Cheung picture Frederick Cheung · Sep 7, 2012

The reflections hash holds this kind of information:

Issue.reflections['assigned_to'].foreign_key

You can also get other information, such as the class (.active_record) or the type of association (.macro). Prior to rails 4.2, the keys of this hash are symbols and not strings.