【问题标题】:Validating polymorphic association type in Rails在 Rails 中验证多态关联类型
【发布时间】:2012-05-11 17:13:53
【问题描述】:

我正在开发一个控制器,该控制器创建一个具有多态 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 是关联的有效类型数组。

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

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

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

【问题讨论】:

    标签: ruby-on-rails validation activerecord mongoid polymorphic-associations


    【解决方案1】:

    回答得太早了,没有得到您正在查看多态关联。

    对于一般关联,请使用reflect_on_all_associations

    但是,对于一些多态关联,没有办法知道所有可以实现关联的类。对于其他一些,您需要查看类型字段。

    【讨论】:

      【解决方案2】:

      对于您的验证,您不必获取所有可能的多态类型。您只需要检查指定的类型(例如,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 是否包含有效的类。

      【讨论】:

        猜你喜欢
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多