Kristiyan Tsvetanov
Kristiyan Tsvetanov

Reputation: 1047

Rails - seeding with paperclip images

I found several questions on that topic and I followed the instructions to seed my models with images. However, when seeding I get an error "PG::UndefinedColumn: ERROR: column meals.meal_avatar does not exist" even though my model has it. This is my Meal model

class Meal < ActiveRecord::Base
  has_attached_file :meal_avatar, styles: { large: '300x300' }, default_url: '/images/:style/missing.png'
  validates_attachment_content_type :meal_avatar, content_type: /\Aimage\/.*\Z/
end

This is the migration

  def self.up
    change_table :meals do |t|
      t.attachment :meal_avatar
    end
  end

The allowed parameters in the controller

  def meal_params
    params.require(:meal).permit(:name, :meal_avatar)
  end

The way I seed the image(It is out of context but you can get the idea)

meal_seed = [
  {
    name: "Salad",
    meal_avatar: File.new("app/assets/images/salad.jpg")
  }
]
meal_seed.each do |meal_params|
  meal = category.meals.find_or_create_by(meal_params)
end

Any idea why my seeds fail :? Thank you!

Upvotes: 0

Views: 277

Answers (2)

VijayGupta
VijayGupta

Reputation: 675

try this it may be work for you!

meal_seed.each_with_index do |meal_params, index|
  Meal.create!(meal_params)  
end

Upvotes: 0

DickieBoy
DickieBoy

Reputation: 4956

This has to do with find_or_create_by. I believe the find happens before the paperclip object has been processed, which is why its trying to look for the column meal_avatar.

Separate them out into two lines.

meal_seed.each do |meal_params|
  avatar = meal_params.delete(:meal_avatar)
  meal = category.meals.find_or_initialize_by(meal_params)
  meal.meal_avatar = avatar

  meal.save
end

Upvotes: 1

Related Questions