访问Rails中的关联

mr_*_*urf 5 activerecord ruby-on-rails associations

有没有办法让我可以获得特定模型在Rails中所属的模型列表?

例如:

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
Run Code Online (Sandbox Code Playgroud)

希望这有点儿意义!

Ott*_*tto 6

这将为您提供描述给定模型上的关联和其他内容的对象哈希Model.reflections.您希望散列中的所有值都是Reflection::AssociationReflection类.此代码应该为您提供所需的数组:

association_names = []
Model.reflections.each { |key, value| association_names << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) }
Run Code Online (Sandbox Code Playgroud)