首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Faker为存储在S3中的头像设定种子

从Faker为存储在S3中的头像设定种子
EN

Stack Overflow用户
提问于 2018-12-01 01:23:52
回答 1查看 631关注 0票数 2

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

代码语言:javascript
复制
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

这是用户的模型,也就是学生模型(这是正确设置的,并且在通过网站上传图像时有效):

代码语言:javascript
复制
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并尝试播种这些数据,它就不再对我起作用了。

EN

回答 1

Stack Overflow用户

发布于 2018-12-01 01:38:02

尝试如下所示:

代码语言:javascript
复制
#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

更新:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53562171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档