LoginSignup
0
0

More than 5 years have passed since last update.

アプリケーションの作成2

Last updated at Posted at 2017-02-28
app/views/layouts/application.htmlerb


app/views/layouts/application.htmlerb
から「window.scrollTo(0.document.body.scrollHeight);」を削除。
投稿一覧画面では新しい投稿が上に表示されるような並び順にするため、「window.scrllTo(0.docment.body.scrollHeight);」の自動スクロール処理を削除した。

app/assets/stylesheets/mystyle.css


app/assets/stylesheets/mystyle.cssにコード追加。

.btn-space-20 {
  margin-top: 20px;
}

投稿一覧画面の新しい投稿ボタンの位置調整に使います。

app/views/layouts/_navbar.html.erb


app/views/layouts/_navbar.html.erb
のテキスト変更
「+投稿一覧」

app/views/posts/show.html.erb


app/views/posts/show.html.erbを作成し次のコード入力。
show.blade.phpを新規作成します。投稿に対するコメントを表示する箇所は後で追加します。

app/controllers/posts_controller.rb


app/controllers/posts_controller.rbからコード削除

def delete_all_post
  Post.delete-all
  redirect_to posts_path
  end
end

派生アプリでは全投稿を削除すつボタンは使用しないので削除します。

app/controllers/posts_controller.rb


app/controllers/posts_controller.rbのindexを次のコードに変更

def index
  @post = Post.all.order(created_at: :desc)
end

order(created_at: :desc)を使って新しい投稿が上に来るようにソートする。

app/controllers/posts_controller.rb


app/controllers/posts_controller.rbに次のコード追加。

def show
  @post = Post.find(params[:id])
end

新しい画面(投稿内容)のためのshowアクションを追加します。

config/routes.rb


config/routes.rbから次のコード削除。

post "delete_all_post" => "post#delete_all_post"

delete-all_postアクションを削除したので、ルートも削除。
さらに、次のコードを変更
showアクションを追加したのでルートも追加。
ruby:config/routes.rb
resources :posts, only: [:index, :new, :create, :show]

app/controllers/posts_controller.rbに次のコード追加。
せんたくされた投稿を削除するための処理。

app/controllers/posts_controller.rb
def destroy
  @post = Post.find{params[:id]}
  @post.destroy

  redirect_to posts_path

config/routes.rbのコード変更。
destroyアクションのルートを追加します。
ruby:config/routes.rb
resources :posts, only: [:index, :new, :create, :show, :destroy]

app/views/posts/indwx.html.erbの次のコードを変更。
action属性にPostControllerのdestroysアクションのルート設定。
destroyアクションにパラメータとしてpost.idを渡す。

app/views/posts/indwx.html.erb
<form action="<%= post_path(:id => post.id) %>" method="post">

rails g model Commentを実行。
Commentモデルのほかにcommentsテーブルのマイグレーションスクリプトも生成されます。

rails g model Comment

app/models/comment.rbのCommentクラスに次のコードを追加。
UserとCommentは1対多の関係があり、Commetは多側なのでリレーションの定義ではbelongToを使います。

app/models/comment.rb
class Comment < ApplicationRecord
  belong_to :user

  validates :message, presence: true
end
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