2

我正在開發一個控制器,該控制器創建一個具有多態belongs_to關聯的模型。我現在在做什麼來找到它所屬的模型如下:驗證Rails中的多態關聯類型

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延遲加載類,所以爲了能夠找到這個東西,我不得不在初始化時明確加載所有模型。

回答

6

爲了驗證您不必獲取所有可能的多態類型。您只需檢查指定的類型(即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是否包含有效的類。

0

回答得太快,沒有看到您正在查看多態關聯。

對於一般的協會,請使用reflect_on_all_associations

但是,對於某些多態關聯,沒有辦法知道所有可以實現關聯的類。對於其他人,你需要看看類型字段。