基于具有多态关联的 paerpclip 中的模型生成不同的图像样式

Posted

技术标签:

【中文标题】基于具有多态关联的 paerpclip 中的模型生成不同的图像样式【英文标题】:Generate different image styles based on models in paerpclip with polymorohic association 【发布时间】:2014-12-29 17:35:45 【问题描述】:

有什么方法可以根据具有多态关联的回形针中的模型生成不同的图像样式。

我有

图片模型:

class Picture
  .....
  belongs_to :imageable, :polymorphic=>true
  has_attached_file :local_image,
  :styles => lambda |f|
    ['image/jpeg', 'image/jpg','image/png', 'image/gif'].include?(f.content_type) ? 
      :thumb => "40x40>",
      :small => "115x115>", 
      :medium => '300x300>',
      :large => "500x500>"  : 
  
  ...
end

用户模型:

class User
  has_many :pictures, :as=> :imageable
end

组模型:

class Group
  has_many :pictures, :as=> :imageable 
end

我想要拇指,小号只适合用户模型,中号,大号只适合团体模型。我试过这个https://leomayleomay.github.io/blog/2013/07/30/polymorphic-image-styles-using-paperclip/ 但它不适用于新图片,仅适用于现有图片

【问题讨论】:

【参考方案1】:
##show only thumb size image to user
##using first as has_many associations
u=User.find 1
u.pictures.first.local_image.url(:thumb)


##show all other remaining sizes to group..using first as has_many associations
g=Group.find 1
g.pictures.first.local_image.url(:small)
g.pictures.first.local_image.url(:medium)
g.pictures.first.local_image.url(:large)

更多信息请参考this

【讨论】:

实际上我想根据关联模型生成图像样式。此代码用于显示现有的图像样式,但我希望如果不需要,则不应生成额外的样式图像。 嗨@AmanGarg,如果您已指定,它们将被生成。因此您必须使用 after_commit :get_only_thumb_images, on: :create Callback 或从您已经指定的模型中删除它们。

以上是关于基于具有多态关联的 paerpclip 中的模型生成不同的图像样式的主要内容,如果未能解决你的问题,请参考以下文章

具有多态实体的子类关联表的 SQLAlchemy 设置

CakePHP中具有直接多态关联的MySQL错误

Ruby on Rails: :include 与子模型的多态关联

使用关注点扩展具有角色的用户模型

rails中的多态关联

Apollo 中的缓存正在避免 GraphQL 解决多态关联