gpt4 book ai didi

ruby-on-rails - 在 Rails 中验证多态关联类型

转载 作者:行者123 更新时间:2023-12-04 05:56:21 25 4
gpt4 key购买 nike

我正在开发一个 Controller ,它创建一个具有多态 belongs_to 关联的模型。我现在做的是找到它所属的模型如下:

 def find_polymorphic_model(classes)
classes_names = classes.map { |c| c.name.underscore + '_id' }

params.select { |k, v| classes_names.include?(k) }.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end

raise InvalidPolymorphicType
end

其中 classes 是关联的有效类型数组。

这种方法的问题是我必须在 Controller 中记住我正在创建的模型允许哪些类型。

有没有办法找到某个多态 belongs_to 关联允许哪些类型?或者也许我做错了,我不应该让多态 Controller 在不将其嵌套在多态资源(在路由器中)中的情况下暴露出来?

我还认为 Rails 延迟加载类这一事实可能存在问题,因此为了能够找出这个问题,我必须在初始化时显式加载所有模型。

最佳答案

对于您的验证,您不必获取所有可能的多态类型。您只需检查指定的类型(例如,taggable_type 属性的值)是否合适。你可以这样做:

# put it in the only_polymorphic_validator.rb. I guess under app/validators/. But it's up to you.
class OnlyPolymorphicValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
polymorphic_type = attribute.to_s.sub('_type', '').to_sym
specified_class = value.constantize rescue nil
this_association = record.class.to_s.underscore.pluralize.to_sym

unless(specified_class.reflect_on_association(this_association).options[:as] == polymorphic_type rescue false)
record.errors[attribute] << (options[:message] || "isn't polymorphic type")
end
end
end

然后使用:

validates :taggable_type, only_polymorphic: true

检查 :taggable_type 是否包含有效类。

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

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