【问题标题】:Rails, active storage, Error message when I try to attach a photoRails,活动存储,当我尝试附加照片时出现错误消息
【发布时间】:2020-08-12 09:39:51
【问题描述】:

我正在尝试将照片直接附加到seed.rb 中的实例。但我认为这不是问题,因为它在控制台中也不起作用。 当我运行 rails db:seed 时,我收到以下错误消息: Errno::ENOENT: No such file or directory @ rb_sysopen - ../app/assets/images/image.jpg

这是我的模型:

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

这是我的种子文件:

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

我还将require "active_storage/engine" 包含在我的config/application.rb 文件中。

这是我的应用程序文件夹,也是我的 seed.rb 和 image.jpg 文件所在的位置。貌似链接有问题?

有人知道我做错了什么吗? 谢谢!

【问题讨论】:

    标签: ruby-on-rails image activerecord rails-activestorage seed


    【解决方案1】:

    你需要通过Rails.root获取你的应用路径

    在你的种子文件中改成这个并尝试

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

    您也可以将其存储在变量中

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

    另外,添加文件存在的条件

    File.exist? file_path
    

    【讨论】:

    • 非常感谢您的快速回复。但我实际上发现了问题所在。我的storgage.yml 文件丢失了,也是一个宝石。我会稍后发布解决方案,也许它会对某人有所帮助!再次感谢!
    • 其实你是对的!与此同时,我忘记了我是从服务器获取图像,而不是直接从应用程序中的图像文件夹中获取图像。我刚刚尝试了您的解决方案,它奏效了!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2018-06-22
    • 1970-01-01
    相关资源
    最近更新 更多