When I wanted to add an image to the seed file, I was worried because I didn't know how to write it, so I will describe it below. This is written by a beginner, so please point out any mistakes.
When dealing with images with rails, I think that you often use Active Storage or Carrier Wave. Reference: ActiveStorage vs CarrierWave
This time, we are using Active Storage, so please proceed only if you are using it.
We will describe the initial data of the user created using devise in the seed file.
The columns in the user model look like this.
db/schema.rb
t.string "name", null: false
t.text "profile"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "avatar"
t.boolean "admin", default: false
In addition to the columns included in devise by default, avatar
is added as a column for user images.
(In addition, name, profile, and admin are added.)
% rails s
Please check if you can register the image from the browser.
: avatar
as a parameter.If you can add it without any error, let's write it in the seed file.
db/seeds.rb
user = User.create(name: "Saya",
profile: "It is an office lady.",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true)
First of all, execute the following command.
% rails db:migrate:reset
% rails db:seed
Let's check if there is no problem with the above and the initial data is reflected. If there is no problem, add an image (avatar).
First, add the images you want to use to app/assets/images
.
This time I added a file called cat.jpg
.
Why did you define user
earlier?
That is to attach the image.
Add avatar to the description of the seed file earlier.
db/seeds.rb
user = User.create(name: "Saya",
profile: "It is an office lady.",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true)
user.avatar.attach(io: File.open(Rails.root.join('app/assets/images/cat.jpg')),
filename: 'cat.jpg')
And
% rails db:migrate:reset
% rails db:seed
Please run the. Let's check with the browser whether it is reflected!
There wasn't much information about ActiveStorage, so I hope it reaches the troubled beginners!
reference Attach file/IO object [Rails 5.2] How to use Active Storage Try new features of Rails6 64 (db: seed edition)
Recommended Posts