【问题标题】:PaperClip for Two Models Error?两个模型错误的回形针?
【发布时间】:2015-05-11 18:48:01
【问题描述】:

我为我的第一个模型安装了 Paperclip,它工作正常,但是当我尝试将它添加到我的第二个模型时出现错误。我基本上是想为我创建的两个模型上传两个图像。这是错误:

undefined method `image_content_type' for #<IosCourse:0x007fd4bb3bfaf0>

这是我的第一个模型(Rubycourse.rb):

class Rubycourse < ActiveRecord::Base
  acts_as_votable
  has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  has_many :reviews
end

这是第二个模型(IosCourse.rb):

class IosCourse < ActiveRecord::Base
  attr_accessor :image_file_name
  has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-3.2 paperclip


    【解决方案1】:

    您也应该将所需的列(用于回形针)添加到第二个模型。

    Paperclip 将包含最多四个属性(所有属性都以该附件的名称为前缀,因此如果您愿意,每个模型可以有多个附件)并为它们提供友好的前端。这些属性是:

    • |附件|_文件名
    • |附件|_file_size
    • |附件|_content_type
    • |附件|_updated_at

    因此,基本上您需要编写/运行迁移以将这些属性添加到第二个模型:

    class AddImageColumnsToIosCourse < ActiveRecord::Migration
      def self.up
        add_attachment :ios_courses, :image
      end
    
      def self.down
        remove_attachment :ios_courses, :image
      end
    end
    

    Paperclip 提供了一个迁移生成器来生成该文件:

    $ rails generate paperclip IosCourse image 
    

    另一个想法:如果您将有不同的带有附件的模型,并且这些附件将具有相似的逻辑(验证、额外方法等),那么创建多态可能是一个好主意具有所有这些回形针逻辑的模型(即附件)并将这个新模型与您的其余模型相关联。

    class Attachment < ActiveRecord::Base
      belongs_to :attachable, polymorphic: true
    
      # Paperclip stuff
      has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
      validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
    end
    
    class Rubycourse < ActiveRecord::Base
      has_one :attachment, as: :attachable
    end
    
    class IosCourse < ActiveRecord::Base
      has_one :attachment, as: :attachable
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多