LoginSignup
3
3

More than 3 years have passed since last update.

Rails:createアクションの仕組み

Last updated at Posted at 2020-09-12

動機

newとcreateの役割に困惑したためのメモ作成

new

新しく作成する場合は
new.html.hamlとnewアクションがまず使用される

create

newの中のformで作成した内容を元にDBへ登録するアクションがcreate

以下のコードが一連の流れです。

def create
    @task = Task.new(task_params)
    if @task.save
      redirect_to task_path(@task), notice: 'Task is create'
    else
      render :new
end

データの取得

@task = Task.new(task_params)

private
  def task_params
    params.require(:task).permit(:title, :content)
  end

newで取得した内容を@taskに引数として渡している
引数にはprivateメソッドで取得した値をいれる

requireは必要という意味
permitは許可という意味
なので:taskモデルの:titleと:contentは許可するけど他の値は許可しないよというようなデータを取得している(ストロングパラメータ)

save

if @task.save
      redirect_to task_path(@task), notice: 'Task is create'
    else
      render :new

取得したデータが保存できたら
showページに遷移する
できなかったらnewページに遷移する

重要

createアクション内もインスタント変数にしている理由は
createからnewページへ遷移する際newページで使用されるインスタンス変数はcreateアクション内にインスタンス数があればこれを利用できる

すなわち
保存されなかったデータも残したままnewページを呼び出すことができる

3
3
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
3
3