1
0

Railsアプリケーションを立ち上げる

Posted at

プログラミング学習を始めて約2か月。
理解しているのか謎なので自分なりにまとめてみようと思います。

アプリの内容

タイトル、名前、内容を投稿するアプリです。
(初心者なので細かな設定はしていません。基本の動作を理解するためのものです。)

手順

1.新規アプリの立ち上げ
2.一覧機能実装
3.投稿機能実装
4.保存機能実装

アクション

・index  一覧表示
・new   新規投稿
・create   保存

1.新規アプリ雛形作成

今回は「practice_app」という名前でアプリを作ります。

%rails _7.0.0_ new practice_app -d mysql
%rails db:create #データベース作成

モデルの作成。命名規則は「単数形」

%rails g model post

カラムの追加。項目は「タイトル」・「内容」・「名前」、型はタイトルと名前は1行以上になることはないので「string」、内容は長い文章を想定して「text」としました。

_create_posts.rb
t.string :title
t.text :content
t.string :name

マイグレート実行

% rails db:migrate

2.一覧機能(index)

コントローラーを作成。命名規則は「複数形」

% rails g controller posts 

コントローラーの設定。(アクションを定義)

app/controller/posts_controller
def index
  @posts = Post.all
end
#すべての投稿を@postsに格納

ビューの作成。一覧表示なのでファイル名はindex.html.erb

index.html.erb
<% @posts.each do |post| %>
  タイトル:<%= post.title %><br>
  内容:<%= post.content %><br>
  投稿者:<%= post.name %><br>
<% end %>

ルーティングの設定

routes
root to: 'posts#index'  #postsコントローラーのindexアクション
resources :posts, only: [:index]

3.投稿機能

コントローラーの設定。

posts_controller
def index
  @posts = Post.all
end
def new
  @post = Post.new
end

ルーティングの設定

routes
root to: 'posts#index'
resources :posts, only: [:index, :new]

ビューの設定 new.html.erb作成。

new.html.erb
<%= form_with model: @post, local: true do |form| %>
  <%= form.text_field :title, placeholder: "タイトル" %><br>
  <%= form.text_area :content, placeholder: "投稿内容" %><br>
  <%= form.text_field :name, placeholder: "投稿者" %><br>
  <%= form.submit 'POST' %>
<% end %>

4.保存機能

コントローラーの設定

posts_controller
def index
  @posts = Post.all
end
def new
  @post = Post.new
end
def create
  Post.create(post_params)
  redirect_to action: :index
end

private
def post_params
  params.require(:post).permit(:title, :content, :name)
end

ルーティングの設定

routes
root to: 'posts#index'
resources :posts, only: [:index, :new, :create]

実際に作ってみたところ一応形になりました!
今回の気付き
・ルーティング、コントローラーのアクションは初めから使うアクションが分かっていたので一度にindex,new,createを記述したほうが良いのか?

これから機能やレイアウトを追加していきながらさらに理解を深めていきます!

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