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

入力されたデータからユーザーを特定する方法

0
Posted at

目次

①結論
②find_byメソッドとは
③find_byメソッドの使い方

①結論

find_byメソッド使用する。

②find_byとfindの違い

データ取得方法の違い
  1. @user = User.find(params[:id])

  2. @user = User.find_by(email:params[:email],password:[params:password])

1については、idの値を指定してデータを取得している

2については、カラムを指定してデータを取得している

③find_byメソッドの使い方

入力されたデータをもとにユーザーなどを見つけ出したいときに使用する。
例えばログイン機能を実装する場合、メールアドレスやパスワードを入力してログインするが、これは入力されたデータをもとにユーザーを探しているので、find_byメソッドを使用することになる。

余談ですが、ユーザーを探した結果が存在する場合と存在しない場合で場合を分けて考える必要がある。
下記のように記述する。

 def アクション名
  @user = User.find_by(email:params[:email],password:params[:password])
  if @user 
   redirect_to ◯◯◯◯
  else
  render ◯◯◯◯
  end
 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?