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

User関係の処理出忘れていたところ

ユーザーの新規登録、ログイン、一覧、詳細ページ、または機能を追加できた。
しかしまだなくなっているものがある。
プロゲートを参考にしている。
それは
・バリデーションをかける
・フラッシュメッセージをつける
・例外処理をする
・エラーメッセージを表示させる

・ユーザー画像を設定する
・session[:user_id]を使いログイン中にさせる。
・条件分岐で表示内容を変える

まずuserモデルのバリデーションをかけよう。

バリデーションをかける

user.rb
class User < ApplicationRecord
  validate :name, {presence: true}
end

こんな感じかな?
見てみよう。

user.rb
class User < ApplicationRecord
  validates :name, {presence: true}
  validates :email, {presence: true, uniqueness:true}
  validates :password, {presence: true, uniqueness:true}
end

何かパスワードは何かあったような気がするが今はどうでもいい。
後でする。

rails consoleで確かめてみよう

irb(main):001:0> user = User.new
=> #<User:0x000000011347f400 id: nil, name: nil, email: nil, passwo...
irb(main):002:0> user.save
  TRANSACTION (0.3ms)  BEGIN
  User Exists? (0.5ms)  SELECT 1 AS one FROM `users` WHERE `users`.`email` IS NULL LIMIT 1
  User Exists? (0.5ms)  SELECT 1 AS one FROM `users` WHERE `users`.`password` IS NULL LIMIT 1
  TRANSACTION (0.3ms)  ROLLBACK
=> false

これでfalseになっている。

フラッシュメッセージをつける

users_controller.rb
.
.
.
  def update
    @user = User.find_by(id: params[:id])
    @user.name = params[:name]
    @user.email = params[:email]
    @user.password = params[:password]
    if @user.save
      flash[:notice] = "更新されました。"
      redirect_to "/users/#{@user.id}"
    else
      render "users/edit"
    end
  end
.
.
.
application.html
.
.
.
    </header>

    <% if flash[:notice] %>
      <div class="flash">
        <%= flash[:notice] %>
      </div>
    <% end %>
    <%= yield %>
.
.
.

これで表示される。

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?