views:

200

answers:

2

Is there a way that I can get a list of the models that a particular model belongs to in Rails?

For example:

class Project < ActiveRecord::Base
  has_one :status
  ...
end

class Task < ActiveRecord::Base
  has_one :status
  ...
end

class Status < ActiveRecord::Base
  belongs_to :project
  belongs_to :task

  # this is where I want to be able to pass in an array of the associations' class
  # names (to be used for checking input) rather than having to do w%{ project task } 
  # which leaves it open to failure if I add new associations in future
  validates_inclusion_of :status_of, :in => ?
  ...
end

Hope this makes some kind of sense!

+2  A: 

You can use one array to define the associations and use in the validations like:

BELONGS_TO_LIST = w%{ project task }
BELONGS_TO_LIST.each {|b| belongs_to b}
validates_inclusion_of :status_of, :in => BELONGS_TO_LIST
Abdullah Jibaly
Thanks. Not the method I was thinking of but it works a treat.
Urf
+3  A: 

This will get you a hash of objects describing the associations and other things on a given model Model.reflections. You want all the values in the hash that are Reflection::AssociationReflection classes. This code should get you the array you want:

association_names = []
Model.reflections.each { |key, value| association_names << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) }
Otto
Exactly what I was looking for! Many thanks.
Urf
Awesome answer. Spot on.
Tilendor