Search code examples
ruby-on-railsimageactiverecordrails-activestorageseed

Rails, active storage, Error message when I try to attach a photo


I am trying to attach a photo to instances in the seed.rb directly. But I don't think that is the issue, because it doesn't work in the console either. When I run rails db:seed I get this error message: Errno::ENOENT: No such file or directory @ rb_sysopen - ../app/assets/images/image.jpg

Here is my Model:

class Restaurant < ApplicationRecord
  restaurant_types = ["chinese", "italian", "japanese", "french", "belgian"]
  has_one_attached :photo
  has_many :reviews, dependent: :destroy
  validates :name, :address, :category, :phone_number, presence: true
  validates :category, inclusion: { in: restaurant_types, message: "%{value} is not a valid size" }
end

Here is my seed file:

require 'open-uri'
require "faker"
puts "deleting all restaurants and reviews"

Review.delete_all
Restaurant.delete_all

puts Restaurant.count
puts Review.count

puts "creating new restaurants"

20.times do
  name = Faker::Restaurant.name
  address = Faker::Address.community
  phone = Faker::PhoneNumber.cell_phone
  category = ["chinese", "italian", "japanese", "french", "belgian"].sample
  restaurant = Restaurant.create(name: name, address: address, phone_number: phone, category: category)
  restaurant.photo.attach(io: File.open('../app/assets/images/image.jpg'), filename: 'image')
end

And I also included require "active_storage/engine" in my config/application.rb file.

And here is my application folder and where both my seed.rb and image.jpg files are located. Apparently there is something wrong with the link?

enter image description here

Anyone knows what I am doing wrong? Thanks!


Solution

  • You need to get the path of your application by Rails.root

    change to this in your seed file and try

    restaurant.photo.attach(io: File.open(Rails.root.join("app", "assets", "images", "image.jpg")), filename: 'image.jpg')
    

    You can store this in a variable also

    file_path = Rails.root.join("app", "assets", "images", "image.jpg")
    restaurant.photo.attach(io: File.open(filepath), filename: 'image.jpg')
    

    Also, add a condition for file exist

    File.exist? file_path