我有一个自定义模型,它使用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
时,我得到了
CCD_ 2。
有人能建议我可以做什么更改吗?以便attachment.attachable
适用于这两种附件类型。
例如
当我执行类似的操作时
att = Attachment.find(3)
#假设它将可附加类型返回为User所以att.attachable返回用户对象
但是当我执行att = Attachment.find(3)
#假设它将可附加类型返回为UserLogo所以att.attachable返回异常wrong constant name UserLogo
如何从两种附件类型访问User
对象。感谢
保留您的可附加类型"User",它将是干净的多态类型。定义"附件"模型内的类型字段,该字段具有两个值徽标&文件
关联将更新如下
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
作为可附加类型,则它不遵循多态关联,因此定义自定义关联。
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
第二种方法:创建扩展User
类的UserLogo
类。它将找到具有相同用户数据的UserLogo