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.reflectionsReflection::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

1 つの配列を使用して関連付けを定義し、次のような検証で使用できます。

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 に答える