【问题标题】:Seeding profile pictures stored in S3 from Faker从 Faker 播种存储在 S3 中的个人资料图片
【发布时间】:2019-05-02 21:11:20
【问题描述】:

我正在开发一个 Rails 应用程序,并且我有一个 has_one_attached 个人资料图片用于在 S3 中进行主动存储,我想在我为我的用户播种时从 Faker 为他们的头像图像播种数据。 这是种子代码:

20.times do
  Student.create(
      first_name: Faker::Name.first_name, 
      last_name: Faker::Name.last_name,
      phone_number: Faker::PhoneNumber.cell_phone,
      school_id: School.first.id,
      vehicle_make_model: Faker::Vehicle.make_and_model,
      vehicle_year: Faker::Vehicle.year,
      vehicle_color: Faker::Vehicle.color,
      email_address: Faker::Internet.email,
      password: "password", 
      email: Faker::Internet.email,
      profile_picture: Faker::Avatar.image
  ).save
end

这是 User aka Student 的模型(设置正确并且在通过网站上传图像时有效):

class Student < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  belongs_to :school, optional: true
  has_many :offers
  has_many :comments
  has_many :cars
  has_one_attached :profile_picture
end

我之前已经播种了其余的数据,它工作正常,但是一旦我集成了 S3 并尝试使用这些数据播种,它就不再适合我了。

【问题讨论】:

    标签: ruby-on-rails amazon-s3 seeding faker


    【解决方案1】:

    试试这样的:

    #seed_file
    require 'open-uri'
    
    def image_fetcher
        open(Faker::Avatar.image)
        rescue
        open("https://robohash.org/sitsequiquia.png?size=300x300&set=set1")
    end
    
    20.times do |n|
      s = Student.create(
         ...
         #remove profile_picture from here
      )
    
      s.profile_picture.attach({
         io: image_fetcher,
         filename: "#{n}_faker_image.jpg"
      })
    end
    

    更新:

    require 'faker'
    require 'open-uri'
    
    def image_fetcher
      URI.open(Faker::Avatar.image)
      rescue
      URI.open("https://robohash.org/sitsequiquia.png?size=300x300&set=set1")
    end
    

    【讨论】:

    • 不幸的是,在调用 open uri 时,我收到了 500 错误代码,具体而言
    • OpenURI::HTTPError: 500 内部服务器错误
    • @RoccoDaigler 好的,更新了我的帖子。 500 的原因是一些Faker.image url 无效并抛出错误。确保我发布的所有内容。此外,.save 已删除,因为它不直接创建。
    • 我尝试了完全相同的代码并得到了这个错误: Errno::ENOENT: No such file or directory @ rb_sysopen - robohash.org/sitsequiquia.png?size=300x300&set=set1 @7urkm3n
    • @EltonSantos 我不知道你是怎么做到的。但问题看起来像文件名:“#{n}_faker...”
    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多