MVCファイルのそれぞれの読み方のメモ


MVCファイルのそれぞれの読み方をよく忘れるのでメモ

config / routes.rb
Rails.application...
root 'users#index'
end

view:users/index.html.erb
controller:Users
action:index
url:localhost3000 = root_path


config / routes.rb
Rails.application...
get '/index', to: 'users#index'
end
view: users/index.html.erb
controller: Users
action: index
url: localhost3000/index = index_path


config / routes.rb
Rails.application...
get '/users/new', to: 'users#new'
post '/users', to: 'users#create'
end

form_forなどでdbに新規データを保存するときに使う

controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end

def create
user = User.new(user_params)
# dbはUserテーブルでカラムがname(string), age(integer)を用意しておく
user.save
end

private
# userテーブルには必ず名前と年齢が必要とする
def user_params
params.require(:user).permit(:name, :age)
end
end
end

views/users/new.html.erb

<%= form_for @user do |f| %>
<%= f.label :名前 %%>
<%= f.text_field :name%>
<%= f.label :年齢%>
<%= f.submit_field :age%>
<%= f.submit "新規作成"%>
<% end%>