5

有没有一种方法可以获取特定模型在 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

希望这有某种意义!

4

2 回答 2

6

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

association_names = []
Model.reflections.each { |key, value| association_names << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) }
于 2009-01-26T19:20:25.893 回答
3

您可以使用一个数组来定义关联并在验证中使用,例如:

BELONGS_TO_LIST = w%{ project task }
BELONGS_TO_LIST.each {|b| belongs_to b}
validates_inclusion_of :status_of, :in => BELONGS_TO_LIST
于 2009-01-26T17:27:09.603 回答