Ruby on rails 是否需要在资源控制器`#create`方法中设置实例变量?
具有以下控制器的资源Ruby on rails 是否需要在资源控制器`#create`方法中设置实例变量?,ruby-on-rails,Ruby On Rails,具有以下控制器的资源Foobar: class FoobarController < ApplicationController def new @foobar = Foobar.new(baz: params[:baz]) @foobar.build_data end def create @foobar = Foobar.new(foobar_params) respond_with(@foobar) end # ... end
Foobar
:
class FoobarController < ApplicationController
def new
@foobar = Foobar.new(baz: params[:baz])
@foobar.build_data
end
def create
@foobar = Foobar.new(foobar_params)
respond_with(@foobar)
end
# ...
end
respond_to do |format|
if @foobar.save
flash[:notice] = 'Foobar was successfully created.'
format.html { redirect_to(@foobar) }
else
format.html { render action: "new" }
end
end
?这取决于您响应的内容类型。该选项准确地描述了当您调用
respond\u with
时发生的情况。在您的情况下,在create
操作中,respond\u with
与以下内容相同,假设您在控制器中的respond\u to
调用中未指定html以外的任何其他格式:
class FoobarController < ApplicationController
def new
@foobar = Foobar.new(baz: params[:baz])
@foobar.build_data
end
def create
@foobar = Foobar.new(foobar_params)
respond_with(@foobar)
end
# ...
end
respond_to do |format|
if @foobar.save
flash[:notice] = 'Foobar was successfully created.'
format.html { redirect_to(@foobar) }
else
format.html { render action: "new" }
end
end
唯一需要使用
@foobar
实例变量的情况是,如果存在验证错误并且您的new.html
模板包含@foobar
。如果foobar_参数始终有效,则respond_with
将始终重定向到show
操作,因此不需要实例变量。这取决于您响应的内容类型。该选项准确地描述了当您调用respond\u with
时发生的情况。在您的情况下,在create
操作中,respond\u with
与以下内容相同,假设您在控制器中的respond\u to
调用中未指定html以外的任何其他格式:
class FoobarController < ApplicationController
def new
@foobar = Foobar.new(baz: params[:baz])
@foobar.build_data
end
def create
@foobar = Foobar.new(foobar_params)
respond_with(@foobar)
end
# ...
end
respond_to do |format|
if @foobar.save
flash[:notice] = 'Foobar was successfully created.'
format.html { redirect_to(@foobar) }
else
format.html { render action: "new" }
end
end
唯一需要使用@foobar
实例变量的情况是,如果存在验证错误并且您的new.html
模板包含@foobar
。如果foobar_参数始终有效,则respond_with
将始终重定向到show
操作,因此不需要实例变量