1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyonRailsでtwitter風webアプリケーションの作成 STEP4:投稿機能の一覧表示、新規投稿

Last updated at Posted at 2019-05-25

投稿用のモデル、テーブルの作成

コマンドライン
$ rails g model Tweet body:string user_id:integer
$ rails db:migrate

投稿用のコントローラーの作成

コマンドライン
$ rails g controller Tweets index new create show edit destroy

ルーティングの設定

config/routes.rb
  resources :users do
    resources :tweets, only: [:new,:create]
  end
  get "tweets/index"

ユーザーモデルとツイートモデルを紐付ける

app/models/users.rb
has_many :tweets
app/models/tweets.rb
belongs_to :user

新規投稿用のビューを作成

app/views/tweets/new.html.erb
<h3 class="page-header">今日の出来事をつぶやこう</h3>
<%= form_for([@user, @user.tweets.build]) do |f| %>
<p><%= f.label :body,"投稿内容" %></p>
<p><%= f.text_area :body %></p>
<p><%= f.submit "投稿", class: "btn btn-primary" %></p>
<% end %>

投稿一覧用のビューを作成

app/views/tweets/index.html.erb
<h3 class="page-header">ツイート一覧</h3>
<ul class="list-group">
  <% @tweet.each do |tweet| %>
  <li class="list-group-item">
    <span class="badge text-danger"><%= link_to "[削除]",tweets_destroy_path,method: :delete %></span>
    <%= tweet.body %>
  </li>
  <% end %>
</ul>

tweetコントローラーの設定

app/controllers/tweets_controller.rb
class TweetsController < ApplicationController
  def index
    @tweet = Tweet.all
  end

  def new
    @user = User.find(params[:user_id])
  end

  def create
    @user = User.find(params[:user_id])
    @user.tweets.create(tweet_params)
    redirect_to tweets_index_path
  end

  def destroy
    @tweet = Tweet.find(params[:id])
    if @tweet.destroy
    redirect_to "/",flash: {danger: "投稿を削除しました"}
  end
  end

  private
  def tweet_params
    params.require(:tweet).permit(:body)
  end

ブラウザで投稿機能の確認

スクリーンショット 2019-05-25 16.30.16.png

スクリーンショット 2019-05-25 16.30.56.png

スクリーンショット 2019-05-25 16.31.07.png

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?