【问题标题】:single model to have two file attachment columns - Rails 4 + Paperclip单个模型具有两个文件附件列 - Rails 4 + Paperclip
【发布时间】: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


    【解决方案1】:

    保留您的可附加类型“用户”,这将是干净的多态。在“附件”模型中定义 type 字段,其中包含两个值 logofile

    协会将更新如下

    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
    

    我建议您有不同的附件样式取决于它的类型(徽标/文件)。附件类型的验证也因类型而异。

    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
    

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

    更新 - 回答更多问题

    第一种方式:如果你在Attachment中使用UserLogo作为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 类扩展User 类。它将找到具有相同用户数据的 UserLogo

    【讨论】:

    • 嗨@ray,感谢您的回复。我仍然有一个例外,我已经用示例更新了这个问题,你能检查一下吗?谢谢
    • 所以我的主要问题是当附件类型为徽标时如何访问用户对象
    • @opensource-developer 我没有尝试过,所以不太确定,但它应该可以工作,请检查我的答案中的更新
    • @opensource-developer 我的荣幸 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多