Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@kure

【Rails】モデル作成の小さなサンプルメモ

More than 1 year has passed since last update.

作成するモデル

  • Page
    • title: text
    • content: text

メモ

モデル/マイグレーションの作成

console
% rails g model Page title:text content:text
Running via Spring preloader in process 14662
      invoke  active_record
      create    db/migrate/20180527151423_create_pages.rb
      create    app/models/page.rb
      invoke    test_unit
      create      test/models/page_test.rb
      create      test/fixtures/pages.yml

出来たマイグレーションファイル↓

20180527151423_create_pages.rb
class CreatePages < ActiveRecord::Migration[5.1]
  def change
    create_table :pages do |t|
      t.text :title
      t.text :content

      t.timestamps
    end
  end
end

できたモデルクラス↓

page.rb
class Page < ApplicationRecord
end

できたフィクスチャ↓

pages.yml
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

one:
  title: MyText
  content: MyText

two:
  title: MyText
  content: MyText

マイグレーション

% rails db:migrate

できたテーブル↓

# \d pages
 id         | bigint                      | not null default nextval('pages_id_seq'::regclass)
 title      | text                        | 
 content    | text                        | 
 created_at | timestamp without time zone | not null
 updated_at | timestamp without time zone | not null

フィクスチャの使用

% rails db:fixtures:load

確認↓

rails_console
irb(main):003:0> Page.all
  Page Load (0.3ms)  SELECT  "pages".* FROM "pages" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Page id: 980190962, title: "MyText", content: "MyText", created_at: "2018-05-28 02:14:05", updated_at: "2018-05-28 02:14:05">, #<Page id: 298486374, title: "MyText", content: "MyText", created_at: "2018-05-28 02:14:05", updated_at: "2018-05-28 02:14:05">]>
irb(main):004:0> Page.find(1)
postgres_console
# select * from pages;
id         | 980190962
title      | MyText
content    | MyText
created_at | 2018-05-28 02:14:05.849503
updated_at | 2018-05-28 02:14:05.849503
-----------+---------------------------
id         | 298486374
title      | MyText
content    | MyText
created_at | 2018-05-28 02:14:05.849503
updated_at | 2018-05-28 02:14:05.849503
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kure

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?