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.

Railsのインスタンス変数(view)について

Last updated at Posted at 2019-06-09

インスタンス変数(view)について

前提

属性name <- validates true

Controller(createアクション)

Railsでtodoアプリを開発する際に、createアクションでの検証エラーを画面に表示する方法を忘れそうなので記述しとく

例えば通常(ただ登録するだけ)では

tasks_controller.rb
def create
  task = Task.new(xxx_params)
  task.save!
  redirect_to xxx_url
end

private
  def xxx_params
    params.require......
  end

となる

だが
このままでは名前が空欄のまま登録した際にエラーを表示できなくなる
対処法

tasks_controller.rb
def create
  @task = Task.new(xxx_params)
  
  if @task.save
    redirect_to xxx_url or @task 
  else
    render :new  
  end
end

1. save!をsaveにしたのはsaveは失敗した場合戻り値にfalseを返すから
2. render :new としたのは結果がfalseだった場合にnew.html.erbを再度表示させるため
3. taskを@taskにしたのはエラーの際にnew.html.erbを表示される、この時にインスタンス変数@taskであればnewページに戻ったとしても、前回入力した値を引き継いでくれる

これはeditアクションにも応用できる

tasks_controller.rb
  def edit
    @task = Task.find(params[:id])
  end

  def update
    @task = Task.find(params[:id])

    if @task.update(xxx_params)
      redirect_to xxx_url or @task
    else
      render :edit
    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?