【问题标题】:Accessing associations in Rails在 Rails 中访问关联
【发布时间】:2009-01-26 16:55:40
【问题描述】:

有没有一种方法可以在 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

希望这有某种意义!

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    这将为您提供描述给定模型Model.reflections 上的关联和其他内容的对象哈希。您希望哈希中的所有值都是Reflection::AssociationReflection 类。这段代码应该可以得到你想要的数组:

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

    【讨论】:

      【解决方案2】:

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

      BELONGS_TO_LIST = w%{ project task }
      BELONGS_TO_LIST.each {|b| belongs_to b}
      validates_inclusion_of :status_of, :in => BELONGS_TO_LIST
      

      【讨论】:

      • 谢谢。不是我想的方法,但它很管用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多