首页 > 解决方案 > 模型的未定义方法“imageable_type”

问题描述

我想使用多态Photo模型来处理不同模型的图像。每个imageable_type都有不同的标准。类型Item将具有版本控制并且是公共的,而类型User将具有加密并存储在私有 S3 存储桶中。我想我可以做这样的事情:

class Photo < ApplicationRecord
 if imageable_type == "Item"
  include ImageUploader::Attachment(:image)
 elsif imageable_type == "User"
  #do something else
 end
    
 belongs_to :imageable, polymorphic: true
 validates_presence_of :image
end

class User < ApplicationRecord
 has_many :photos, as: :imageable, dependent: :destroy
end

class Item < ApplicationRecord
 has_many :photos, as: :imageable, dependent: :destroy
end

但是这样做会产生错误:NoMethodError (undefined method 'imageable_type' for Photo (call 'Photo.connection' to establish a connection):Class).

如何根据关联的类型将不同的过程应用于多态模型?

标签: ruby-on-rails

解决方案


这不起作用,因为您的代码是在类上定义的,而不是在实例上定义的。类当然没有imageable_type属性,只有实例有。

根据您想要做什么,您需要将其移至这样的方法。

class Photo
  def upload #
    if imageable_type == "Item"
      #do something
    elsif imageable_type == "User"
      #do something else
     end
  end
end

我们需要了解更多信息,criteria以便在此处提出适当的解决方案。


推荐阅读