Create DB, add contents, save, delete with rails console.
$ rails g model User name:string email:string
id | name(string) | email(string) |
---|---|---|
1 | alice | [email protected] |
2 | tom | [email protected] |
$ rails db:migrate
$ rails console
> user = User.new(name:"alice", email:"[email protected]")
> user.save
> user = User.all
> user[0]
> user = User.all
> user0 = user[0]
> user[0].name = "alice_alice"
> user[0].save
> user[0].destroy
Validation is a mechanism to verify whether the data is correct before the object is saved in the DB.
class User < ApplicationRecord
validates :email, {uniqueness: true}
end
class Post < ApplicationRecord
validates :content, {presence: true, length: {maximum: 140}}
end
id | name(string) | email(string) |
---|---|---|
1 | alice | [email protected] |
2 | tom | [email protected] |
Add user image information to this!
$ rails g migration add_image_name_to_users
Files are added to the migration folder / db / migration /
.
Contents of /db/migration/20201010_create_post.rb
The change method was automatically generated in the migration file created by rails g model
.
So I was able to reflect the changes with rails db: migrate
without any particular changes.
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t| #Create a table named posts
t.string :name #Create a column named name whose data is string
t.string :email #Create a column named email with data string
t.timestamps
end
end
end
This time, we will add a column, so we need to write the contents of the change method by ourselves.
class AddImageNameToUsers < ActiveRecord::Migration[5.0]
def change
add_column :uses, :image_name, :string #Table name, column name, data type
end
end
Execute the contents of the change method
$ rails db:migrate
Use File.write
.
$ rails console
> File.write("public/aaa.txt", "Hello World")
# File.write(Where to write,Contents)
Use the File.bin write
and read
methods.
Write the read ʻimage to
public / user_images / "1.jpg " `and save it.
if image = params[:image]
@user.image_name = "#{@user.id}.jpg "
File.binwrite("public/user_images/#{@user.image_name}", image.read)
end
Recommended Posts