0
0

More than 1 year has passed since last update.

createの条件分岐ができない

Last updated at Posted at 2022-12-21

まえがき

新規ユーザーの登録ページにて情報を登録できたらredirect_toでトップページへ。
登録できなかった場合はrenderで新規登録ページに遷移するという分岐を設定したかったのですが・・・
登録できても、できなくてもトップページに遷移してしまうという症状に悩んでいました。
解決策が分かったので、記録します。

参照先:
Taroken Fintech様:【Rails】createメソッドとnew+saveメソッドの使い分けを解説 
お陰様で解決できました!ありがとうございます!:bow_tone3:

以下がその時の記述です。

def create
    if Prototype.create(prototype_params)
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def prototype_params
    params.require(:prototype).permit(:title, :catch_copy, :concept, :image).merge(user_id: current_user.id)
  end
end

結論

条件分岐ではcreateメソッドは使わずに、new + saveメソッドを使うこと!

なぜなら

・ createメソッドは保存できる、できないに関わらず戻り値にインスタンスを返すのでtrue扱いになってしまう。
・ saveメソッドは実行結果にtrue、falseを返してくれる。

このように直したらキチンと分岐できました!

def create
    @prototype = Prototype.new(prototype_params)
    if @prototype.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def prototype_params
    params.require(:prototype).permit(:title, :catch_copy, :concept, :image).merge(user_id: current_user.id)
  end
end

あとがき

createメソッドあれば、saveメソッドは使わないと思っていました・・・

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