Beetlejuice
Beetlejuice

Reputation: 4425

List reference columns of a active record model

using Rails 3.2, there is a way to find out if a column is a reference column to other model?

I don't want to rely in "_id" string search in the name.

thanks.

UPDATE:

I need to iterate over all columns and made a special treatment in references columns, something like:

result = Hash.new
self.attribute_names.each do |name|
  if self[name]
    result[name] = self[name]

    if name is reference column
       insert xxx_description (from the other model) in hash.
    end
  end
end

I will return this hash as json to client.

{name: 'joseph', sector_id: 2, sector_name: 'backend'...}

Where sector_name, is person.sector.name...

thanks.

Upvotes: 1

Views: 649

Answers (2)

m_x
m_x

Reputation: 12554

alternative method if you don't know the name of the association :

Post.reflect_on_all_associations(:belongs_to).map &:foreign_key 
# => ['author_id','category_id']

Upvotes: 3

reto
reto

Reputation: 16732

See http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html

Post.reflections[:comments].primary_key_name # => "message_id"

How to get activerecord associations via reflection

Upvotes: 0

Related Questions