お猿のつぶやきアプリ

Ruby初心者でも超簡単に実装出来るTwitterの簡易版を作ってみました。

● Progateのrubyは終わったよ!

● とりあえず簡単なアプリを作ってみたい!

● いきなりrailsチュートリアルはむず過ぎる!!

● 超初心者でも作れるものが欲しい!!

という方のために絶対に挫折しない簡単なツイッターアプリのチュートリアルを作ってみました。

【アプリの説明】

お猿がつぶやく超シンプルなアプリ。

ログイン機能、プロフィール編集はありません。

【railsの理解に役立つもの】

railsの全体図を分かりやすくまとめたものを作成してます!

こちらをみながらやると大変スムーズかと思います!!



【下準備】

始める前にcloud9の設定と画像をこちらからダウンロードし、"pic.png"と名前をつけて保存してください。(app/assetes/imageフォルダ内へ保存)


【環境】

ruby 2.5.1

rails 5.2.1

cloud9


cloud9についてはこちらが詳しく載ってるので参考にしてみてください。


【チュートリアル本編 設定】

早速作っていきましょう!!

ここら辺はやったことある人は飛ばして下さいcloud9のターミナルでMYSQLをインストールしてください

$ sudo yum install mysql-devel

yes or noが出るので

y

でmysqlを実行。

mysqlを実行してください。

$ sudo service mysqld start

bundlerをインストールしてください。

$ gem install bundler

phpmyadmin(データベースの中身を簡単に見えるようにするもの)をインストールしてみましょう。詳しくはのちに説明します。

$ sudo yum install phpmyadmin


【チュートリアル本編 作成編】

●rails newコマンド

ターミナルから 

rails new "アプリケーション名" (monkey_tweet)

とすることでそのアプリケーション名のアプリを簡単に作ることができます。

rails _5.2.1_ new monkey_tweet -d mysql

今回はmysqlを同時に作成、且つrailsのバージョンを5.2.1にしています。

cloud9のフォルダに”monkey_tweet”ができていると思います。

●Gemとは?

railsはgemというライブラリがあります。有名なものはdeviseというgemがあります。これはdeviseをインストールするだけで簡単にログイン機能ができちゃうってやつです。gemをアプリに追加するにはGemfileにgemを追加します。

左のフォルダが並んでいる中から"Gemfileを探して開いてください。

pry-railsというでバックに必要なgemをインストールしてみます。gemファイルの一番下に以下を追加してみましょう!

$ gem 'pry-rails'
$ bundle install
# これでpry-railsというGemをインストール

●bundle update
bundle updateを行うことによってGemfileに記述した内容をGemfile.lockに記録することができます。

$ cd monkey_tweet
$ bundle update
$ bundle install

これでgem fileに記載したpry-railsというgemをインストールできました。

データベースを作ります。

$ rake db:create

続いてツイートコントローラーを作っていきます。

$ cd monkey_tweet

$ rails g controller tweets 

続いてtweets controllerを編集します。

routes.rbを編集します。

Rails.application.routes.draw do
  get 'tweets' => 'tweets#index'
end


styleseets/tweets.scssは以下をコピペ

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
body, html {
  height: 100%;
  background-color: #ddd;
}

.logo{
   display: flex;
   justify-content: space-between;
}

.logo img{
  width: 35px;
  height: 35px;
  padding: 5px 10px;
}

h1, h2, h3, h4, h5, h6, p, body {
  font-size: 14px;
  color: #4a4a4a;
  font-family: sans-serif;
  margin: 0;
  padding: 0;
}

.clearfix:after{
  display: block;
  content: "";
  clear: both;
}

.wrapper{
  min-width: 960px;
  }

header{
  height: 45px;
  background-color: white;
}

.button {
  font-family: "Yu Gothic", YuGothic, Verdana, 'Hiragino Kaku Gothic ProN','Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ Pro W3', 'メイリオ', Meiryo, sans-serif;
  text-align: right;
  padding: 3px 20px;
}
.btn-border {
  display: inline-block;
  max-width: 180px;
  text-align: left;
  border: 2px solid #9ec34b;
  font-size: 16px;
  color: #9ec34b;
  text-decoration: none;
  font-weight: bold;
  padding: 6px 16px;
  border-radius: 4px;
  transition: .4s;
}

.btn-border:hover {
  background-color: #9ec34b;
  border-color: #cbe585;
  color: #FFF;
}

h1{
  height: 46px;
  line-height: 46px;
  font-size: 18px;
}

h2{
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  text-align: center;
}

.contents{
  height: 100%;
  width: 600px;
  margin: 5px auto 0;
  background-color: white;
}

form{
  width: 600px;
  background-color: white;
  padding: 5px 0 0;
}

.input-box{
  float: left;
  width: 530px;
}

.input-box input{
  width: 100%;
  margin: 0 0 10px 0;
}

form img{
  border: 1px solid #ccc;
  border-radius: 5px;
  float: left;
  height: 24px;
  margin: 0 5px 5px 33px;
}

.submit-button{
  width: 70px;
  margin: 10px 25px 0 0;
}

form textarea{
  width: 500px;
  border: 1px solid #ccc;
}

.button-box{
  float: right;
  height: 70px;
}

.message{
  min-height: 100px;
  width: 598px;
  margin: 0 auto;
  background-color: #fff;
  border: 1px solid #bbb;
  border-bottom: none;
}

.message img{
  border: 1px solid #ccc;
  border-radius: 5px;
  float: left;
  height: 48px;
  margin: 10px;
}

.message_box{
  float: left;
  height: 100px;
  width: 505px;
  padding: 9px 0 10px;
}

.user_name{
  font-weight: bold;
  line-height: 18px;
}

.time{
  color: #bbb;
}

.text{
  line-height: 18px;
}

.flash{
  background-color: #00a8a8;
  color: white;
  text-align: center;
}

tweet modelを作っていきます。

$ rails g model tweet

db/migrate/20XXXXXXXXXXXXX(作成日)_create_tweets.rbというファイルを

dbフォルダのmigrateフォルダから探して以下の通り編集します。

textカラムを作成します。

class CreateTweets < ActiveRecord::Migration[5.2]
  def change
    create_table :tweets do |t|
      t.text        :text
      t.timestamps null: true
    end
  end
end

これはマイグレーションファイルなのでターミナルでrake db:migrateを行いデータベースに反映していきます。

$ rake db:migrate

tweetsコントローラーの編集

@tweetsに全てのツイートを入れます。

class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all
  end

end

ターミナルで以下実行してみましょう!

$ rails c
$ Tweet.create(text: "バナナが食べたいよーーー")
$ exit

index.html.erbのファイルをapp/views/tweetsフォルダから作成。

(viewフォルダの上で右クリックでnewファイル)

<header>
  <div class="logo">
     <a href="/tweets"> <%= image_tag 'pic.png' %></a>
    <h1>猿のつぶやき</h1>
    <div class="button">
    <a href="/tweets/new" class="btn-border">投稿する</a>
    </div>
  </div>
</header>
<!--フラッシュメッセージの表示-->
<% if flash[:notice] %>
  <div class="flash">
    <%= flash[:notice] %>
  </div>
<% end %>
<div class="contents">
  <% @tweets.each do |tweet| %>
    <div class="message clearfix">
      <%= image_tag 'pic.png' %>
      <div class="message_box">
        <p class="user_name">
          お猿ざえもん
        </p>
        <p class="text">
          <p>コメント:  <%= tweet.text %></p>
        </p>
      </div>
    </div>
  <% end %>
</div>


これで投稿の一覧表示部分が実装できました。

続いて投稿部分を作っていきます。

configのroutes.rbを編集します

Rails.application.routes.draw do
  get 'tweets' => 'tweets#index'
  get 'tweets/new' => 'tweets#new'
end

続いてコントローラー

class TweetsController < ApplicationController
  def index
    @tweets = Tweet.all
  end

  def new
  end
end

app/views/tweets/new.html.erb

<div class="contents">
  <h2>投稿する</h2>
  <%= form_tag('/tweets', method: :post, class: "clearfix") do %>
    <img src="/assets/pic.png">
    <textarea cols="30" name="text" rows="4"></textarea>
    <div class="button-box">
      <input type="submit" class="submit-button">
    </div>
  <% end %>
</div>

postのルーティングを作っていきましょう!

Rails.application.routes.draw do
  get 'tweets' => 'tweets#index'
  get  'tweets/new' => 'tweets#new'
  post 'tweets' => 'tweets#create'
end

コントローラーでcreateアクションを実装し、投稿が終わったらtweets(indexページ)にダイレクトしています。

class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all
  end

  def new
  end

  def create
    if Tweet.create(tweet_params)
     redirect_to tweets_path, notice: "投稿が完了しました"
    end
  end

  private
  def tweet_params
    params.permit(:text)
  end

end

これで一通りの実装が終わりました!!

cloud9の

preview>preview running applicationからビューを見てみましょう!!

(you are on rails!!が出てきたらURLの最後に"tweets"をつけてみて下さい)

こんなのが出来れば完成です!!おめでとうございます!!

色々いじって楽しんで下さいね!!

完全趣味でやってるのでシェア、RTして頂けるとモチベーションになります!!よろしくお願いいたします。

(第二段はツイートの非同期処理を考えてます!)

Twitter@first_code_
















この記事が気に入ったらサポートをしてみませんか?