为什么我要在控制器中用两种方法创建一个新的模型对象?
Why do I create a new model object in two methods in a controller?
根据互联网的各个部分,我有以下代码:
控制器
class StudiesController < ApplicationController
def new
require_user
@study = Study.new
end
def create
@study = Study.new(study_params)
if @study.save
flash[:success] = "You made it!"
redirect_to root_path
else
flash[:danger] = "Uh oh—something went wrong"
redirect_to study_path
end
end
end
查看
<%= form_for(@study, url: {action: :create}, class: "study-form") do |f| %>
<%= f.text_field :title %><br>
<div class="btn-submit">
<%= f.submit "I studied today!", class: "btn btn-primary margin-top" %>
</div>
<%= end %>
它有效,但我的问题是:为什么我需要 Study.new
调用两次?如果我已经在 new
中调用它,为什么还要在 create
中调用它?
当您在新方法中使用Study.new创建新对象时,它用于在保存前创建新记录和呈现新表单。之后,当您在创建方法中使用 Study.new(study_params) 时,它将根据表单提交的值构建对象,并将数据保存在数据库中 table.
在新方法中创建的 Study 实例在视图中用于呈现 HTML。
当 HTML 被发送到浏览器时,Study 实例不再存在——它从未被保存,创建只是为了帮助呈现 HTML。
当从浏览器提交表单时,参数被传递给要创建的实例赋值,但首先必须创建一个新的 Study 实例来赋值。
此实例随后被保存。
根据互联网的各个部分,我有以下代码:
控制器
class StudiesController < ApplicationController
def new
require_user
@study = Study.new
end
def create
@study = Study.new(study_params)
if @study.save
flash[:success] = "You made it!"
redirect_to root_path
else
flash[:danger] = "Uh oh—something went wrong"
redirect_to study_path
end
end
end
查看
<%= form_for(@study, url: {action: :create}, class: "study-form") do |f| %>
<%= f.text_field :title %><br>
<div class="btn-submit">
<%= f.submit "I studied today!", class: "btn btn-primary margin-top" %>
</div>
<%= end %>
它有效,但我的问题是:为什么我需要 Study.new
调用两次?如果我已经在 new
中调用它,为什么还要在 create
中调用它?
当您在新方法中使用Study.new创建新对象时,它用于在保存前创建新记录和呈现新表单。之后,当您在创建方法中使用 Study.new(study_params) 时,它将根据表单提交的值构建对象,并将数据保存在数据库中 table.
在新方法中创建的 Study 实例在视图中用于呈现 HTML。
当 HTML 被发送到浏览器时,Study 实例不再存在——它从未被保存,创建只是为了帮助呈现 HTML。
当从浏览器提交表单时,参数被传递给要创建的实例赋值,但首先必须创建一个新的 Study 实例来赋值。
此实例随后被保存。