0

I am having a problem while validating on an image field in model on a rails4 app.

class ModelA < ActiveRecord::Base
  validates :name, presence: true
  validates :logo, presence: true
  has_attached_file :logo, styles: {
    thumb: '100x100>',
    square: '200x200#'
}

In the migrations, a new instance of this model is to be created.

def migrate(direction)
    super
    if direction == :up
      obj = Model1.create!(:name => "Test")

This is failing as the required field is not specified and If I am explicitly specifying a default image, then the table does not have the necessary column yet.

This migration runs if I am removing the image (in this case, logo) validation before migration and thereafter specify the image file and details like its name. Is there a better way to setup this model?

Sumit Bisht
  • 1,507
  • 1
  • 16
  • 31

1 Answers1

0

I've figured this out. The problem was in the migrations - the logo migration (as well as validation) was added afterwards of this Object creation in the migration. I added the logo to the Model1.create! and moved this migration After these migrations to solve the error.

Hence, my migrations roughly are:

 def change
  create_table :... do |t|
    t.string :name
    t.timestamps
  end

Followed by addition of paperclip column

def self.up
  change_table :... do |t|
    t.attachment :logo
  end
end

And added the model in another migration that was coming after them.

def migrate(direction)
  super
  if direction == :up
    logo_img = File.open('app/assets/images/logo-big.png', 'rb')
    Model1.create!(:name => "TestObj", :logo => logo_img )
Sumit Bisht
  • 1,507
  • 1
  • 16
  • 31