【发布时间】:2019-04-22 03:35:16
【问题描述】:
我有一个自定义模型,它在导轨中使用附件模型。 我的附件模型看起来像这样
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
has_attached_file :file, styles: { logo: ['200x50>',:png] }
end
另一个使用附件的模型看起来像这样
class User < ActiveRecord::Base
has_many :attachments, as: :attachable, dependent: :destroy
end
我希望用户模型有另一个不同于我已经设置上传徽标的附件,类似这样
has_one :user_logo, -> {where attachable_type: "UserLogo"}, class_name: "Attachment", foreign_key: :attachable_id, foreign_type: :attachable_type, dependent: :destroy
但是当我尝试访问attachment.attachable 时,我得到了
undefined UserLogo as **UserLogo** is not a model。
任何人都可以建议我可以进行哪些更改,以便attachment.attachable 适用于两种附件类型。
例如
当我执行这样的事情时
att = Attachment.find(3) #假设它以用户身份返回可附加类型
所以 att.attachable 返回用户对象
但是当我执行
att = Attachment.find(3) #假设它返回可附加类型作为 UserLogo
所以 att.attachable 返回异常wrong constant name UserLogo
如何从两种附件类型访问User 对象。谢谢
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 paperclip