单个模型有两个文件附件列 - Rails 4 + Paperclip

single model to have two file attachment columns - Rails 4 + Paperclip

我有一个自定义模型,它使用 rails 中的附件模型。 我的依恋模型看起来像这样

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) #假设它 returns 可附加类型为用户 所以 att.attachable returns 用户对象

但是当我执行 att = Attachment.find(3) #假设它 returns 可附加类型为 UserLogo 所以 att.attachable returns 异常 wrong constant name UserLogo

如何从两种附件类型访问 User 对象。谢谢

保留您的可附加类型 'User',这将是干净的多态性。在 'Attachment' 模型中定义 type 字段有两个值 logo & file

协会将更新如下

class User < ActiveRecord::Base

has_many :attachments, -> {where type: "file"}, as: :attachable, dependent: :destroy  
has_one :user_logo, -> {where type: "logo"}, class_name: "Attachment", foreign_key: :attachable_id, foreign_type: :attachable_type, dependent: :destroy

end

我建议您根据附件的类型使用不同的样式 (logo/file)。附件类型的验证也因类型而异。

has_attached_file :file, styles: ->(file){ file.instance.get_styles }

validates_attachment_content_type :file, :content_type: [..], if: -> { type == 'logo' }

validates_attachment_content_type :file, :content_type: [..], if: -> { type == 'file' }


def get_styles
  if self.type == 'logo'
    style1
  elsif self.type == 'file'
    style2
  end
end

请更新状态或您进一步查询的任何问题。

更新 - 回答进一步的问题

第一种方式:如果你使用UserLogo作为Attachment中的attachable_type,那么它不遵循多态关联所以定义自定义关联。

belongs_to :resource,
  -> { |attachment| ['User', 'UserLogo'].include? attachment.attachable },
  class_name: 'User',
  foreign_key: :attachable_id

belongs_to :belongs_to :attachable,
  -> { |attachment| ['User', 'UserLogo'].exclude? attachment.attachable_type },
  class_name: :attachable_type,
  foreign_key: :attachable_id

第二种方式: 创建 UserLogo class 扩展 User class。它将找到具有相同用户数据的 UserLogo