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 1 year has passed since last update.

Rails 新規登録フォームを作成する

Posted at

はじめに

基本は備忘録
Qiitaにすごく助けられている

新規登録フォーム

今回はユーザー登録を参考に使うが、新規投稿でも似たような作り方
Userモデル・Controllerは生成済み
*bcrypt*は設定済み
users_ControllerやUser_Modelはログイン機構を参照
bcryptを使う際の注意点
新規登録時にpasswordpassword_confirmationを使用する

新規登録フォームの作り方

# view側
# model: に newアクションで生成したインスタンス変数をset
<div>
  <%= form_with(model: @user, local: true) do |f| %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>
</div>
# Controller
def new
  @user = User.new
end

def create
# User.create(name: params[:user][:name]..)をhashで一度で
# Usesr.create(params[:user])だとセキュリティー的にエラー
@user = User.create(user_params)
  if @user.save
  session[:user_id] = @user.id
  flash[:notice] = "ログインしました"
  # redirect_to user_path(@user.id)の省略
  # "/users/#{@user.id}"
  redirect_to @user
  else
  # render("/users/new")の省略
  render 'new'
  end
end


private

def user_params
  # ストロングパラメータの定義
  # paramsのどのハッシュのどのカラムを取得するか設定
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?