How to test if is a property is a foreign key


How could i test if the property with a certain name, is a foreign key
(the foreign key relation is declared in the model, not in the table)

belongs_to :city, :class_name => “City”, :foreign_key => “CITY_ID”

  • my property for this example is “CITY_ID”
  • i don’t want to test if it has “_id” in the name, the properties
    that are foreign keys may not respect the Class_id rule, further if i
    find that it’s a foreign key, how cand i found the related class.?
  • is there an API command for this?

You may find this project interesting.


From what i’ve read, right on the first page they are going the other
way I want. Due to the nature of the project i must put the relation in
the model, i’m not allowed to modify the database schema.(and the schema
does not have de fk specified).

thank u for the anser, does rails has equivalent for my functions?

knowing an attribute name i want to know if it is used in a belong to


def self.attribute_links_to_a_class?(aatribute)
larray = reflect_on_all_associations(:belongs_to)
lreturn = false {|n| if n.primary_key_name.eql?(aatribute);lreturn=true

knowing an attribute name i want the linked class to be returned

def self.if_attribute_links_to_a_class_return_class(aatribute)
larray = reflect_on_all_associations(:belongs_to)
lreturn = nil {|n| if
n.primary_key_name.eql?(aatribute);lreturn=larray.index(n) end}
if lreturn
return Object.const_get(larray[lreturn].class_name.humanize)
return nil

On 1/30/07, P. Pantouffe [email protected] wrote:

Reflecting on associations might get you halfway there:

class Account < AR
has_many :users

Account.reflect_on_association :users
=> #<ActiveRecord::Reflection::AssociationReflection:0x202491c
@active_record=Account, @primary_key_name=“account_id”,
@macro=:has_many, @name=:users, @options={}>

Account.reflections will show you all associations

Fire up ./script/console and play around.

Hope this helps.

Zack C.

On 1/31/07, P. Pantouffe [email protected] wrote:


Here is a one liner that is simpler.

self.reflect_on_all_associations(:belongs_to).map{ |r|
r.primary_key_name }.include?(attr)

  return nil


This syntax might be better suited for your second method:


Keep in mind that if the relation is of certain types like :through or
:polymorphic then the class_name() method will throw an error. You’ll
need to check the options {} on the reflection:

reflection.options[:polymorphic] || reflection.options[:through]

It might help to play around in ./script/console with your models to
check out the varying behaviour.

Zack C.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs