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

勤怠Aフォロー:(続)Active Recordについて

Last updated at Posted at 2021-07-02

ここまでの内容を踏まえて注意したいこと

# NG
def create
  @user = User.new
    @user.save
  redirect_to xxx_url
end

# better
def create
  @user = User.new
    @user.save!
  redirect_to xxx_url
end

# best
def create
  @user = User.new
    if @user.save
    保存に成功した時の処理
    redirect_to xxx_url
  else
    保存に失敗した時の処理
    # なぜ保存に失敗したか、バリデーションメッセージでユーザーに教えてあげましょう!
    render :new
    end
end
例)seedファイルで初期データを作成するとき

# NG
User.create(name: "aaa", email: "test_a@example.com")
User.create(name: "bbb", email: "test_b@example.com")
User.create(name: "ccc", email: "test_c@example.com")
User.create(name: "ddd", email: "test_d@example.com")
User.create(name: "eee", email: "test_e@example.com")

# OK
User.create!(name: "aaa", email: "test_a@example.com")
User.create!(name: "bbb", email: "test_b@example.com")
User.create!(name: "ccc", email: "test_c@example.com")
User.create!(name: "ddd", email: "test_d@example.com")
User.create!(name: "eee", email: "test_e@example.com")

Active Recordのメソッドはとても便利ですが

Rails 開発ではその恩恵を十分に受けつつ、SQL のクエリも簡単なものぐらいは書けるようにしておきましょう!

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?