0

I am trying to override validates_attachment in Subclass but I notice it only works well with Superclass validation; I wonder why my validates_attachment in subclass doesn't work. Has anybody faced this problem? and how have you solved this problem? Here is an example code:

class Superclass
    validates_attachment :logo, :image_ratio => { :ratio  => {"1:1" => "28", "4:1" => "50", "5:1" => "40"} }
end

class Subclass < Superclass
  validates_attachment :logo, :image_ratio => { :ratio  => {"1:1" => "40", "2:1" => "60"} }
end
Sinal
  • 1,155
  • 5
  • 17
  • 35
  • What error message are you getting? Is it `undefined method validates_attachment` ? Also tell me that which version of paperclip are you using ? – sjain Feb 22 '13 at 07:35
  • I am using paperclip (3.1.4). In fact, there is no error message but validation in Superclass is executed not that in Subclass. – Sinal Feb 22 '13 at 08:58
  • Did you placed both the classes in the same table? – sjain Feb 22 '13 at 09:10
  • I put in the same table. I am using polymorphism concept with this attachmet. – Sinal Feb 22 '13 at 10:02

3 Answers3

1

I suggest that you should put both the class's fields in different tables. It could be possible that you are getting problems because of that.

However if you really want to have only one table for both the classes then I believe that you could use something like this:

validates_attachment :logo, :image_ratio => { :ratio  => {"1:1" => "40", "2:1" => "60"} }, :unless => Proc.new {|attach| attach.type == "SubClass"}

I assumed that you have a attach_type column but depending on how you are determining whether the attachment type is a SubClass, it is left upto you to change it.

You could also try to remove your validates_attachment from the Subclass and instead try with_options in your model, like the following:

with_options :unless => :attach_type == "SubClass" do |attach|
   attach.validates_attachment :logo, :image_ratio => { :ratio  => {"1:1" => "40", "2:1" => "60"}}
end
sjain
  • 23,126
  • 28
  • 107
  • 185
0

This works for me... rails 4

  validates :photo, :presence => true,
  :attachment_content_type => { :content_type => "image/jpg" },
  :attachment_size => { :in => 0..10.kilobytes }
pabloverd
  • 614
  • 8
  • 8
0

Incase anyone else runs into an issue where they need instance access before they can validate I used the following:

class AttachmentDynamicContentTypeValidator < Paperclip::Validators::AttachmentContentTypeValidator
   def validate_each(record, attribute, value)
      @record = record
      super
   end

   def allowed_types
      @record.my_valid_types_array || ["text/plain"]
   end

   def check_validity!; end
end

And in the actual asset instance I added the following:

class Asset < ActiveRecord::Base
   validates :asset, attachment_dynamic_content_type: :asset_content_type
end

Hope that helps someone.

Paul Danelli
  • 994
  • 1
  • 15
  • 25