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'
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.
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.
The correct way for Rails 4.2 is:
Issue.reflections['assigned_to'].options[:foreign_key]
Note that "assigned_to" is a string according to API:
Returns a Hash of name of the reflection as the key and a AssociationReflection as the value.
http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With