LoginSignup
0
0

More than 5 years have passed since last update.

RailsのScaffoldを使わないでアプリケーションを作成してみた。No.2

Last updated at Posted at 2019-02-17

はじめに

自分用備忘録
Scaffoldを使わずにアプリケーションを作成してみる No.2
RailsのScaffoldを使わないでアプリケーションを作成してみた。No.1
No.1で作成した記事に続き、掲示板を作成します

モデルクラスの作成

掲示板を作成するためにモデルクラスを作成

$ rails generate model message name:string email:string title:string body:text image:string password:string

マイグレーションファイルの実行

$ rake db:migrate

テストデータの準備

test/fixtures/テーブル名
新しくフォルダとフォルダ内にmessages.ymlを作成

test/fixtures/messages.yml
yml:
no.1:
  name: 佐藤
  email: sato@test.com
  title: おはようございます!
  body: 本日もよろしくお願いします。
  image: test/imges1.gif
  password: sato
no.2:
  name: 鈴木
  email: suzuki@test.com
  title: こんにちは!
  body: 進捗はどうですか?
  image: test/images2.gif
  password: suzuki

作成後、以下のコマンドを実行するとmessages(テーブル名)にデータが展開されます

$ rake db:fixtures:load FIXTURES=messages

データベースクライアントを起動して、データが反映されたか確認

$ rails dbconsole
=# \d messages

messages テーブルの一覧が確認出来たら、データベースクライアントを閉じる

=# \q

indexファイルを書き換え

message(テーブル名)の内容を表示するために書き換える

app/controllers/messages_controller.rb

app/controllers/messages_controller.rb
class MessagesController < ApplicationController
  def index
    @messages = Message.all 
  end
end

app/views/messages/index.html.erb

app/views/messages/index.html.erb
<table>

<h1>index</h1>
<tr>
<th>NAME</th><th>MAIL</th><th>タイトル</th>       <th>TEXT</th><th>IMAGE</th><th>編集/削除キー</th>
</tr>


<% @messages.each do |message| %>

<tr>
<td><%= message.name %></td>
<td><%= message.email %></td>
<td><%= message.title %></td>
<td><%= message.body %></td>
<td><%= message.image %></td>
<td><%= message.password %></td>
</tr>
<% end %>
</table>

ブラウザで確認
http://IPアドレス:3000/messages
にアクセスして、テーブルの内容が表示されたら完成

まとめ

実際にScaffoldなしで作ってみると動きが把握できて勉強になりました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0