gpt4 book ai didi

ruby-on-rails - 在 Rails 中访问关联

转载 作者:行者123 更新时间:2023-12-04 17:42:29 26 4
gpt4 key购买 nike

有没有办法可以在 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

希望这有点道理!

最佳答案

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

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

关于ruby-on-rails - 在 Rails 中访问关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/480495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com