AHmed Fahad
AHmed Fahad

Reputation: 1

PaperClip for Two Models Error?

I installed Paperclip for my first Model and its working fine but when i try to add it to my second Model i get an error . I am basically trying to have two image uploading for my two Models that i have created. This is the Error:

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

This is my first model (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

This is the second model (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

Upvotes: 0

Views: 147

Answers (1)

markets
markets

Reputation: 7033

You should add the needed columns (for Paperclip) to the second model as well.

Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:

  • |attachment|_file_name
  • |attachment|_file_size
  • |attachment|_content_type
  • |attachment|_updated_at

So, basically you need to write/run a migration to add those attributes to the second model:

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

  def self.down
    remove_attachment :ios_courses, :image
  end
end

Paperclip provides a migration generator to generate that file:

$ rails generate paperclip IosCourse image 

Another idea: If you'll have different models with attachments, and these attachments will have similar logic (validations, extra methods, ...), it's probably a good idea to create a polymorphic model (ie. Attachment) with all these Paperclip logic and associate this new model with the rest of your models.

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

Upvotes: 1

Related Questions