0
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 3 years have passed since last update.

Ruby on Rails での簡単な流れ(rails newから)

Last updated at Posted at 2021-04-15

Railsでアプリ制作

何度も作るうちになんとなくわかってきたので、自分の学習記録として残しておきます。
勉強中のため、間違っている部分があれば教えてください。

rails newで必要なファイルを作成

Dangoというアプリ制作

terminal
rails new Dango --skip-bundle

Herokuでデプロイする時のことを考えて、
--skip-bundle
オプションをつける

つけないと、GemがPCのシステムにinstallされる
(複数のアプリを作成する場合は指定しないとエラーの元となる)


terminal
cd Dango

アプリのディレクトリへ移動

terminal
bundle install --path vendor/bundle

Railsで扱うGemを個々のアプリに分けて扱える
アプリを作成する時はbundle install --path vendor/bundleでGemをインストールすることでアプリごとにGemを自動で切り替えてくれる

初めに開くページを作成(Top)

URLをクリックしたあとに最初に表示されるページを作成する

terminal
rails g controller home top

homeコントローラー作成

topアクション、それに対するview、routes.rbにget home/topができる

app/config/routes.rb
get 'home/top' < 削除 >
root to: 'home#top' < 追記 >

root to: 'home#top'に書き換える

top.html.erb
<h1>このページはルート</>設定しているのでURLの最初のページです</h1>

分かりやすいように書き直しました。書き直さなくても大丈夫です。

terminal
rails s

rails sで動作確認

Webページ上
このページはルート</>設定しているのでURLの最初のページです

が表示されていればOK

Question モデル作成

terminal
rails g model Question title:string body:text

Questionは単数にすること

それぞれのデータがあるため、一つ一つという意味らしい

terminal
rails db:migrate

これをしないとデータベースが作成されない
しないとエラーになる

Questionコントローラー作成

一覧ページ index
詳細ページ show
作成ページ new
保存アクション create
編集ページ edit
更新アクション update
削除アクション destroy

question controller作成

terminal
rails g controller questions index show new edit

questionsは複数にすること

Questionコントローラー作成
保存、更新、削除は画面には表示する必要がないため、後で直接コントローラー内に追記する。

保存、更新、保存はデーターベースの変更のためそのページを表示するのではなく、データーベースを変更する処理のみでよい

routes.rb変更

app/config/routes.rb
root to: 'home#top'

resources :questions < 追記 >

index

questions_controller.rb
class QuestionsController < ApplicationController

< 追記 >
  def index
    @questions = Question.all
  end

end

index.html.erb
<h1>ここはQuestion indexのページです</h1>

<ul>
  <% @questions.each do |q| %>
    <li><%= q.title %></li>
    <li><%= q.body %></li>
  <% end %>
</ul>

<%= q.title %> <%= q.body %> で表示できる

show

questions_controller.rb
class QuestionsController < ApplicationController

< 追記 >
  def show
    @question = Question.find(params[:id) 
  end

end
show.htnl.erb
<h1>ここはQuestion showのページです</h1>

<table>
  <thead>
    <tr>
      <td>Title</td>
      <td>Body</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><%= @question.title %></td>
      <td><%= @question.body %></td>
    </tr>
  </tbody>

</table>

<%= @question.title %> <%= @question.body %> で表示できる

new & edit

questions_controller.rb
class QuestionsController < ApplicationController

< 追記 >
  def new
    @question = Question.new
  end

  def create
    @question = Question.new(question_params)
    if @question.save
      flash[:notice] = 'Question was successfully created.'
      redirect_to question_path(@question)
    else
      render 'new'
    end
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    if @Question.update(question_params)
      flash[:notice] = 'Question was successfully updated.'
      redirect_to question_path(@question)
    else
      render 'edit'
    end
  end

  private
  def question_params
    params.require(:question).permit(:title, :body)
  end

end

private以下のquestion_paramsストロングパラメーターといい安全なデータかを検証してくれるものです

create, updateで失敗したらrenderでそれぞれneweditのフォームを表示するようにしています。

new editについてはフォームヘルパーというものを利用する

_form.html.erbというものを作成することでコードが見やすくなる

_form.html.erbを作成する

_form.html.erb
<%= form_for @question do |f| %>
  <label>Title</label>
  <p>
    <%= f.text_field :title %>
  </p>
  <label>Question</label>
  <p>
    <%= f.text_area :body %>
  </p>
  <p> 
    <%= f.submit %>
  </p>
<% end %>

new.html.erbとedit.html.erbについて以下のようにする

new.html.erb
<h1>ここはQuestion newのページです</h1>

<%= render 'form' %>

edit.html.erb
<h1>ここはQuestion editのページです</h1>

<%= render 'form' %>

<%= render 'form' %>とすることで_form.html.erbのviewがrenderされて表示される

renderとはviewを表示したい時に使用される

validatesを設定する

質問投稿ができても、それが必ず文字で埋まってるという可能性は少ない。そこであらかじめ、空の文字を保存できないように設定することができる。

ここで説明するのは基本的なものなのでrails validatesなどと調べることで色々出てきます。

app/models/question.rb
class Question < ApplicationRecord
  validates :title, presence: true < 追記 >
  validates :body, presence: true  < 追記 >
end

validatesに失敗した時のエラーメッセージ表示

_form.html.erbに以下追記

_form.html.erb
<%= form_for @question do |f| %>
------------ここから-------------
    <% if @question && @question.errors.any? %>
      <%= @question.errors.count %>errors prohibited this obj from being saved:<br>
      <ul>
        <% @question.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>
------------ここまで-------------

    <label>Title</label>
    <p>
      <%= f.text_field :title %>
    </p>
    <label>Body</label>
    <p>
      <%= f.text_area :body %>
    </p>
    <p>
      <%= f.submit %>
    </p>
  <% end %>

今回は、rails newからquestions controllerquestion modelまでを紹介しました。

今後は、ユーザー登録、紐付けなど自分が整理出来次第投稿します。

勉強中のため、説明や記述など間違いがありましたら教えてください。


今後したいこと

  • herokuデプロイ紹介
  • gem 'devise'関連
  • 紐付け関連
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?