ruby-on-rails - 模型的未定义方法“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)
.
如何根据关联的类型将不同的过程应用于多态模型?
解决方案
这不起作用,因为您的代码是在类上定义的,而不是在实例上定义的。类当然没有imageable_type
属性,只有实例有。
根据您想要做什么,您需要将其移至这样的方法。
class Photo
def upload #
if imageable_type == "Item"
#do something
elsif imageable_type == "User"
#do something else
end
end
end
我们需要了解更多信息,criteria
以便在此处提出适当的解决方案。
推荐阅读
- ios - 如果我在 didFinishLaunchingWithOptions 中返回 false 会发生什么?
- mongodb - 我想知道如何在做一个 rest api 函数后传递值,而不在 MongDB 中存储数据
- r - 在函数内使用带有 read.csv 的粘贴
- java - 如何从 Edittext 在自定义列表视图中显示值
- c# - NPOI C# - 将一个工作簿的范围单元格复制到另一个工作簿
- php - 我的 apache 模块目录中没有 libphp*.so
- javascript - SCRIPT5007:无法获取未定义或空引用的属性“关闭”
- css - 子级扩展时如何在嵌套的 CSS 网格中扩展父级高度
- django - “如何修复 'Django' 中的 'csrf' 错误?”
- php - 当我单击按钮以在选择选项作为参考的其他表上显示数据时如何修复“MethodNotAllowedHttpException”