Rails 4.2.6 + 多态 + Carrierwave 0.10 + 条件

Posted

技术标签:

【中文标题】Rails 4.2.6 + 多态 + Carrierwave 0.10 + 条件【英文标题】:Rails 4.2.6 + Polymorphic + Carrierwave 0.10 + conditions 【发布时间】:2016-09-06 06:39:23 【问题描述】:

我有图片模型,它存储来自整个应用程序的图片,在可成像列中我存储图像所有者对象。我希望能够以不同的分辨率保存这些图片。

class Picture < AbstractModel
  belongs_to :imageable, polymorphic: true
  mount_uploader :image, ImageUploader
end

class User < AbstractModel
  has_one :picture, class_name: Picture, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :picture
end

class Event < AbstractModel
  has_one :picture, class_name: Picture, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :picture
end

我在 Carrierwave 中制作了

class ImageUploader < CarrierWave::Uploader::Base
  version :xs if: :for_user? do
    process resize_to_fit: [100, 100]
  end

  private

    def for_user?(_picture)
      # And here I hit the problem!
      # model.is_a? User
    end
end

如何在这里获取图片所有者模型?

Picture 模型上的model 变量引用,我用pry 尝试了所有变量,但没有成功。

当然,我可以将图像链接直接存储在此 sn-p 中的用户和事件中,但是,在现实世界的代码中,我有大约 15 个使用图像的不同模型,我必须提供在 ActiveAdmin CMS 中编辑它的能力(但它是另一个故事:)

更新

主要问题发生在我创建新记录时。所以,我尝试添加inverse_of,但没有帮助。

class Picture < AbstractModel
  belongs_to :imageable, polymorphic: true, inverse_of: :pictures
  mount_uploader :image, ImageUploader

class User < AbstractModel
  has_one :picture, class_name: Picture, as: :imageable, dependent: :destroy, inverse_of: :imageable
  accepts_nested_attributes_for :picture

这是modelfor_user? 方法中的状态

[5] pry(#<ImageUploader>)> ap model
Изображение для  
                :id => nil,
             :image => #<ImageUploader:0x005583dee8f938 @model=#<Picture id: nil, image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>, @mounted_as=:image, @cache_id="1463023347-21567-5096", @filename="rootp_HE_pause-20160113_141810.jpg", @original_filename="rootp_HE_pause-20160113_141810.jpg", @file=#<CarrierWave::SanitizedFile:0x005583dee8cf30 @file="/home/kvokka/proj/volunteers/public/uploads/tmp/1463023347-21567-5096/rootp_HE_pause-20160113_141810.jpg", @original_filename=nil, @content_type="image/jpeg">, @versions=:mini=>#<ImageUploader::Uploader47012442238420:0x005583dee724a0 @model=#<Picture id: nil, image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>, @mounted_as=:image>, :xs=>#<ImageUploader::Uploader47012435752020:0x005583dee72450 @model=#<Picture id: nil, image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>, @mounted_as=:image>, :avatar=>#<ImageUploader::Uploader47012437005860:0x005583dee72428 @model=#<Picture id: nil, image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>, @mounted_as=:image>>,
      :imageable_id => nil,
    :imageable_type => nil,
        :created_at => nil,
        :updated_at => nil

更新2

我已经尝试过 inverse_of: :picture 和 inverse_of: :pictures。语法错误。它使用 inverse_of: :imageable 运行,但结果是一样的。

ImageUploader 的最新版本(为简洁起见,我已将其删掉)是

class ImageUploader < CarrierWave::Uploader::Base
  version :xs do
    process resize_to_fit: [100, 100]
  end

  version :avatar, if: :for_user? do
    process resize_to_fit: [360, 360]
  end

  private

    def for_user?(_)
      model.imageable.is_a? User
    end
end

UPDATE3

我做了一些控制台动作,所以您可以看到,该模型接受嵌套属性。在has_one 关系的情况下,它也可以在没有#inverse_of 方法的情况下工作(这一刻对我来说很棘手)。所以,日志:

[43] pry(main)> ap v = VolunteerCenter.create(title: 'tst', address:'tst', city: City.first, phone:'123456',email: 'mm@mm.ru', description: 'ololo', link: 'http://ddd.ru', picture: (Picture.new( remote_image_url: 'https://retina.news.mail.ru/prev780x440/pic/e5/35/image25749462_adfc024a9b54b718c1a755445661b099.jpg')))
  City Load (0.8ms)  SELECT  "cities".* FROM "cities"  ORDER BY "cities"."id" ASC LIMIT 1
   (0.2ms)  BEGIN
  SQL (0.4ms)  INSERT INTO "volunteer_centers" ("title", "address", "city_id", "phone", "email", "description", "link", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["title", "tst"], ["address", "tst"], ["city_id", 1], ["phone", "123456"], ["email", "mm@mm.ru"], ["description", "ololo"], ["link", "http://ddd.ru"], ["created_at", "2016-05-12 12:13:44.417945"], ["updated_at", "2016-05-12 12:13:44.417945"]]
  SQL (0.3ms)  INSERT INTO "pictures" ("image", "imageable_type", "imageable_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["image", "image25749462_adfc024a9b54b718c1a755445661b099.jpg"], ["imageable_type", "VolunteerCenter"], ["imageable_id", 11], ["created_at", "2016-05-12 12:13:44.421458"], ["updated_at", "2016-05-12 12:13:44.421458"]]
   (2.2ms)  COMMIT
tst 
             :id => 11,
          :title => "tst",
     :created_at => Thu, 12 May 2016 12:13:44 UTC +00:00,
     :updated_at => Thu, 12 May 2016 12:13:44 UTC +00:00,
        :address => "tst",
        :city_id => 1,
          :phone => "123456",
          :email => "mm@mm.ru",
    :description => "ololo",
        :vk_link => nil,
           :link => "http://ddd.ru"

=> nil
[44] pry(main)> ap v.picture
  VolunteerCenter Load (0.6ms)  SELECT  "volunteer_centers".* FROM "volunteer_centers" WHERE "volunteer_centers"."id" = $1 LIMIT 1  [["id", 11]]
Изображение для tst 
                :id => 120,
             :image => #<ImageUploader:0x0055596544d928 @model=#<Picture id: 120, image: "image25749462_adfc024a9b54b718c1a755445661b099.jpg", imageable_id: 11, imageable_type: "VolunteerCenter", created_at: "2016-05-12 12:13:44", updated_at: "2016-05-12 12:13:44">, @mounted_as=:image, @cache_id=nil, @filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @file=#<CarrierWave::SanitizedFile:0x00555963f0c690 @file="/home/kvokka/proj/volunteers/public/uploads/picture/image/120/image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename=nil, @content_type="image/jpeg">, @versions=:mini=>#<ImageUploader::Uploader46921211280280:0x00555966c55890 @model=#<Picture id: 120, image: "image25749462_adfc024a9b54b718c1a755445661b099.jpg", imageable_id: 11, imageable_type: "VolunteerCenter", created_at: "2016-05-12 12:13:44", updated_at: "2016-05-12 12:13:44">, @mounted_as=:image, @parent_cache_id="1463055224-8966-4735", @cache_id=nil, @filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @file=#<CarrierWave::SanitizedFile:0x00555966e89620 @file="/home/kvokka/proj/volunteers/public/uploads/picture/image/120/mini_image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename=nil, @content_type="image/jpeg">, @versions=, @storage=#<CarrierWave::Storage::File:0x00555966e8a4a8 @uploader=#<ImageUploader::Uploader46921211280280:0x00555966c55890 ...>>>, :xs=>#<ImageUploader::Uploader46921211274220:0x00555966c55868 @model=#<Picture id: 120, image: "image25749462_adfc024a9b54b718c1a755445661b099.jpg", imageable_id: 11, imageable_type: "VolunteerCenter", created_at: "2016-05-12 12:13:44", updated_at: "2016-05-12 12:13:44">, @mounted_as=:image, @parent_cache_id="1463055224-8966-4735", @cache_id=nil, @filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @file=#<CarrierWave::SanitizedFile:0x005559659d60c0 @file="/home/kvokka/proj/volunteers/public/uploads/picture/image/120/xs_image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename=nil, @content_type="image/jpeg">, @versions=, @storage=#<CarrierWave::Storage::File:0x005559659d7010 @uploader=#<ImageUploader::Uploader46921211274220:0x00555966c55868 ...>>>, :avatar==>#<ImageUploader::Uploader46921211257860:0x00555966c55840 @model=#<Picture id: 120, image: "image25749462_adfc024a9b54b718c1a755445661b099.jpg", imageable_id: 11, imageable_type: "VolunteerCenter", created_at: "2016-05-12 12:13:44", updated_at: "2016-05-12 12:13:44">, @mounted_as=:image, @parent_cache_id="1463055224-8966-4735", @cache_id=nil, @filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename="image25749462_adfc024a9b54b718c1a755445661b099.jpg", @file=#<CarrierWave::SanitizedFile:0x00555963379328 @file="/home/kvokka/proj/volunteers/public/uploads/picture/image/120/avatar=_image25749462_adfc024a9b54b718c1a755445661b099.jpg", @original_filename=nil, @content_type="image/jpeg">, @versions=, @storage=#<CarrierWave::Storage::File:0x0055596337a390 @uploader=#<ImageUploader::Uploader46921211257860:0x00555966c55840 ...>>>, @storage=#<CarrierWave::Storage::File:0x00555965d85fb8 @uploader=#<ImageUploader:0x0055596544d928 ...>>>,
      :imageable_id => 11,
    :imageable_type => "VolunteerCenter",
        :created_at => Thu, 12 May 2016 12:13:44 UTC +00:00,
        :updated_at => Thu, 12 May 2016 12:13:44 UTC +00:00

UPDATE4

当我在回调方法中使用 pry 运行时会发生这种情况。

class ImageUploader < CarrierWave::Uploader::Base
  version :avatar, if: :for_user? do
    puts 'This line never run'
    process resize_to_fit: [360, 360]
  end

  private

    def for_user?(picture)
      binding.pry
      model.imageable.is_a? User
    end

为了澄清,我关闭了所有验证。 这个回调被调用了 3 次,在第一个 2 User 实例中没有准备好,在最后一个之后回调不起作用。

[46] pry(main)> ap u = User.create(email: 'example@test.com', password: '123456', password_confirmation: '123456', picture: (Picture.create remote_image_url: 'http://onrails.club/uploads/default/29/31f7627609164af8.png'))

From: /home/kvokka/proj/volunteers/app/uploaders/image_uploader.rb @ line 68 ImageUploader#for_user?:

    66: def for_user?(_)
    67:   binding.pry
 => 68:   model.imageable.is_a? User
    69: end

@cache_id                "1463060913-8966-3349"
@file                    #<CarrierWave::SanitizedFile:0x00555963268330 @file="/hom...
@filename                "31f7627609164af8.png"
@model                   #<Picture id: nil, image: nil, imageable_id: nil, imageab...
@mounted_as              :image
@original_filename       "31f7627609164af8.png"
@versions                :mini=>#<ImageUploader::Uploader46921199022860:0x0055596...
[1] pry(#<ImageUploader>)> 

From: /home/kvokka/proj/volunteers/app/uploaders/image_uploader.rb @ line 68 ImageUploader#for_user?:

    66: def for_user?(_)
    67:   binding.pry
 => 68:   model.imageable.is_a? User
    69: end

@cache_id                "1463060913-8966-3349"
@file                    #<CarrierWave::SanitizedFile:0x00555963268330 @file="/hom...
@filename                "31f7627609164af8.png"
@model                   #<Picture id: nil, image: nil, imageable_id: nil, imageab...
@mounted_as              :image
@original_filename       "31f7627609164af8.png"
@versions                :mini=>#<ImageUploader::Uploader46921199022860:0x0055596...
[1] pry(#<ImageUploader>)> 
   (0.3ms)  BEGIN
  SQL (0.7ms)  INSERT INTO "pictures" ("image", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["image", "31f7627609164af8.png"], ["created_at", "2016-05-12 13:48:40.071387"], ["updated_at", "2016-05-12 13:48:40.071387"]]

From: /home/kvokka/proj/volunteers/app/uploaders/image_uploader.rb @ line 68 ImageUploader#for_user?:

    66: def for_user?(_)
    67:   binding.pry
 => 68:   model.imageable.is_a? User
    69: end

@cache_id                nil
@file                    #<CarrierWave::SanitizedFile:0x005559639c6348 @file="/hom...
@filename                "31f7627609164af8.png"
@model                   #<Picture id: 112, image: "31f7627609164af8.png", imageab...
@mounted_as              :image
@original_filename       "31f7627609164af8.png"
@storage                 #<CarrierWave::Storage::File:0x00555963b5add0 @uploader=#...
@versions                :mini=>#<ImageUploader::Uploader46921199022860:0x0055596...
[1] pry(#<ImageUploader>)> 
   (2.9ms)  COMMIT
   (0.2ms)  BEGIN
  User Exists (0.7ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'example@test.com' LIMIT 1
  SQL (0.4ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["email", "example@test.com"], ["encrypted_password", "$2a$11$qq8tVgzISJguKz7oVJWyVO45vW/ujSEsi/ow29w78nC9ByOdjrPYK"], ["created_at", "2016-05-12 13:48:41.761836"], ["updated_at", "2016-05-12 13:48:41.761836"]]
  SQL (0.4ms)  UPDATE "pictures" SET "imageable_type" = $1, "imageable_id" = $2, "updated_at" = $3 WHERE "pictures"."id" = $4  [["imageable_type", "User"], ["imageable_id", 31], ["updated_at", "2016-05-12 13:48:41.764681"], ["id", 112]]
   (2.7ms)  COMMIT
 ,  
                           :id => 31,
                        :email => "example@test.com",
           :encrypted_password => "$2a$11$qq8tVgzISJguKz7oVJWyVO45vW/ujSEsi/ow29w78nC9ByOdjrPYK",
         :reset_password_token => nil,
       :reset_password_sent_at => nil,
          :remember_created_at => nil,
                :sign_in_count => 0,
           :current_sign_in_at => nil,
              :last_sign_in_at => nil,
           :current_sign_in_ip => nil,
              :last_sign_in_ip => nil,
                   :created_at => Thu, 12 May 2016 13:48:41 UTC +00:00,
                   :updated_at => Thu, 12 May 2016 13:48:41 UTC +00:00,
                         :name => nil,
                      :surname => nil,
                        :phone => nil,
                          :dob => nil,
                       :gender => nil,
                       :height => nil,
                        :about => nil,
        :information_source_id => nil,
               :institution_id => nil,
              :clothes_size_id => nil,
                      :city_id => nil,
          :volunteer_center_id => nil,
                     :blood_id => nil,
               :vkontakte_link => nil,
    :medical_contraindications => nil

=> nil

问题仍未解决

【问题讨论】:

【参考方案1】:

如何在这里获取图片所有者模型?

假设您说“图片所有者模型”时指的是用户记录,那么您可以执行以下操作

class ImageUploader < CarrierWave::Uploader::Base
  ...
  def for_user?(picture)
    user = model.imageable
    user.is_a? User
    # => true
  end
  ...
end

来自docs:

picture 参数是要上传的文件对象(这不是你的图片模型的实例)

model 是对您使用此ImageUploader 的实例对象的引用,在您的情况下,它指的是Picture 模型的实例。请注意,这与上面的picture 不同。

既然您知道modelPicture 的一个实例,并且Picture belongs_to :imageable:imageable 是一个多态关联,在您的情况下实际上是一个User 记录,那么您可以访问与我上面的答案相关的记录。但请注意,它可能并不总是 User 记录,因为它是多态关联。

更新

我猜model.imageable 不起作用,因为在从嵌套参数设置后可成像记录为零。

你可以试试

class Picture < AbstractModel
  belongs_to :imageable, polymorphic: true, inverse_of: :picture # WITHOUT s

更新

看起来inverse_of 不适用于多态关联(here 和here)

inverse_of 支持有一些限制:

它们不适用于 :through 关联。 它们不适用于 :polymorphic 关联。 它们不适用于 :as 关联。 对于belongs_to 关联,has_many 反向关联被忽略。

附:这可能很棘手。如果以后有时间,我会尝试重现问题。

【讨论】:

谢谢,但没有帮助。我已经更新了问题并添加了一些细节,所以它可能有用。您的想法将仅用于更新图像,对于新图像,我将捕获所有版本。 谢谢。我试过:图片和:图片。语法错误。它使用 inverse_of: :imageable 运行,但结果是一样的。 我只想验证一件事。您确定关联的 Imageable 记录在控制器中“构建”了吗?您可以通过在def create 中执行以下操作来检查:@picture = Picture.new(picture_params); puts ap @picture.imageable 你能告诉我puts 的输出是什么,并确保这个可成像对象是从嵌套参数“构建”的吗? 如果@picture.imageable 没有被“构建”,你可以先试试this,如果它可以工作的话。 这很奇怪,但它可以工作并且不能同时工作。我已经更新了这个问题。正如我认为的那样,正如我认为的那样,它可以按照这个链接进行操作。 github.com/sferik/rails_admin/wiki/…

以上是关于Rails 4.2.6 + 多态 + Carrierwave 0.10 + 条件的主要内容,如果未能解决你的问题,请参考以下文章

Rails 5 - 使用多态关联 - 渲染视图

Rails 有很多通过有一个多态

具有多态模型的 Rails 范围

rails 4:多态设置基类类型而不是继承

Rails多态命名边缘情况

Rails:如何创建多态关系/友谊模型