Model and table creation

Keep a memorandum of model and table creation.

Create a model in the terminal

rails g model model name

OK if the following log appears

      invoke  active_record
      create    db/migrate/000000000_create_tweets.rb
      create    app/models/Model name.rb
      invoke    test_unit
      create      test/models/Model name_test.rb
      create      test/fixtures/Model name.yml

Model name.rb is created.

Creating a table

A migration file is created when the model is generated. Located in the migrate file in the db folder. Edit this.

class Create model name (uppercase)< ActiveRecord::Migration[6.0]
  def change
    create_table :Model name do|t|
      t.string :name
      t.string :text
      t.text :image
      t.timestamps
    end
  end
end

t. The "type" is followed by the "column name".

Type of type

string: string text: long string integer: integer float: floating point decimal: Decimal with high precision datetime: date and time timestamp: timestamp time: time date: date binary: binary data boolean : Boolean

Perform migration

rails db:migrate

OK if the following log appears

== 20xxxxxxxxxx CreateTweets: migrating =====================================
-- create_table(:tweets)
   -> 0.0148s
== 20xxxxxxxxxx CreateTweets: migrated (0.0149s) ============================

Finally, restart the local server with rails s, and if you can confirm that the data is saved with rails c, you're done

Recommended Posts

Model and table creation
Rails model and table naming conventions
Class and model
Create table and add columns
About Ruby and object model
[Java] Loop processing and multiplication table
RSpec ~ Task model validation test creation
Relationship between database and model (basic)
Ruby on Rails model creation / deletion command