ruby 我是否需要为种子数据设置活动存储?

5sxhfpxr  于 2023-04-20  发布在  Ruby
关注(0)|答案(2)|浏览(96)

我正在做一个最后的项目,在后端使用ruby/rails和active record,在前端使用react。还在开始阶段,我正在制作一些种子数据,以便我能够使用。
我也打算播种一个单一的用户,但我后来计划在我的项目中为用户配置文件图片实施活动存储。我应该考虑到我现在播种的用户,并且已经有活动存储设置,或者我可以在以后担心吗?
现在还没有花太多的时间来学习它,只是想让项目的框架继续下去,并计划以后深入学习它。
下面是我已经创建的用户迁移:

class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :name
      t.string :photo
      t.string :username
      t.string :password_digest

      t.timestamps
    end
  end
end

这是我计划在没有设置活动存储的情况下播种的用户

user = User.create([
  {
    username: "test", 
    password: "test",
    photo: "https://uxwing.com/wp-content/themes/uxwing/download/peoples-avatars/no-profile-picture-icon.png"
   }
])
xkftehaa

xkftehaa1#

skeleton不需要配置主动存储,主动存储只是将附件文件按地址转换到数据库。

但是这种方法是错误的,我的建议是-使用https://shrinerb.com/
它们比主动存储更容易

h7wcgrx3

h7wcgrx32#

ActiveStorage是一个Rails组件,旨在与Rails应用程序一起上传文件。
在你的例子中,你只是简单地添加一个字符串(照片url)作为模型的属性。如果你想上传一个照片文件,你必须将has_one_attached :photo添加到User模型中,并从迁移中删除t.string :photo
你的种子的修复方法是这样的:

user = User.create(username: 'test', password: 'test', photo: 'https://uxwing.com/wp-content/themes/uxwing/download/peoples-avatars/no-profile-picture-icon.png')

如果您要设置附件的种子:

user = User.new(username: 'test', password: 'test')
user.photo.attach(io: File.open(Rails.root.join('vendor', 'assets', 'photos', 'no-profile-picture-icon.png')), filename: 'photo1', content_type: 'image/png')
user.save

user = User.new(username: 'test', password: 'test')
    
photo = URI.parse("https://uxwing.com/wp-content/themes/uxwing/download/peoples-avatars/no-profile-picture-icon.png").open
user.photo.attach(io: photo, filename: "no-profile-picture-icon.png")
user.save

相关问题