ruby-on-rails 如何使用rails主动存储在seed文件中添加图片url?

mctunoxg  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(95)

最近从Rails 4升级到Rails 7.0.4.3
我现在得到一个错误

Could not find or build blob: expected attachable, got #Tempfile:/var/folders/m3/5b_093ms4n7254zlxjr2fthw0000gn/T/open-uri20230418-66934-yzytt1

Seed.rb

require 'open-uri'

spot1 = Spot.create(name: 'Spot 1', description: 'This is spot 1', latitude:42.0, longitude:-73.0, maxGuests: 2, price: 200, address: 'address' , city: 'forbidden_city', host_id: user1.id)

spot1.photos.attach(URI.parse('https://www.example.com/example.jpg').open, filename: "example.jpg")

spots_controller.rb

def create
        @spot = Spot.new(spots_params)

        if @spot.save
            render :show 
        else 
            render json: @spot.errors.full_messages, status: 422
        end

    end

    private
    def spots_params
        params.require(:spots).permit(:name, :description, :latitude, :longitude, :maxGuests, :price, :address, :city, photos: [])
end

播种工作没有我试图附加一个图像
我已经尝试将照片保存到公共s3存储桶
spot1.photos.attach(io: open('https://example-seeds.s3.amazonaws.com/example.jpg'), filename: "example.jpg")
并得到此错误消息

No such file or directory @ rb_sysopen.

这两种方法都用于更新前的工作。
谢谢你的任何建议。

bogh5gae

bogh5gae1#

你需要使用这样的语法

require 'open-uri'

spot1.photos.attach(io: URI.open("https://some.domain/example.jpg"), filename: "example.jpg")

相关问题