def update
@name = account.name # I'm guessing, here, because accessing `name` in the edit action seems to be cut
render ‘edit’ and return unless account.update(params)
end
def edit
@name = Account.find(params[:id]
end
class AccountsController < ApplicationController
before_action :set_account, only: [:show, :edit, :update, :destroy]
# GET /accounts/1/edit
# this method can actually be omitted completely
# rails will implicitly render the view if found
def edit
end
# PATCH /accounts/1
def update
if @account.update(account_params)
redirect_to @account,
success: 'Account updated'
else
render :edit
end
end
# ...
private
def set_account
@account = Account.find(params[:id])
end
def account_params
params.require(:account)
.permit(:name, :foo, :bar, :baz)
end
end
2条答案
按热度按时间zf2sa74q1#
更新操作在编辑方法中是否有示例变量?
不,原因是:
1.你向
edit
发出一个请求,rails会创建一个控制器的示例(在这里你设置@name)1.你提交表单,这是一个由Rails处理的新请求,它将创建一个你的控制器的(新)示例。
你可能会得到你想要的东西,就像这样:
但更规范的方法是在变量中保存一个帐户示例
并在视图中使用它(如
form_for @account
)。但这可能适合也可能不适合您的用例。91zkwejq2#
没有。
当你的Rails服务器收到一个请求时,路由器会尝试匹配一个路由和相应的控制器/动作组合。然后路由器将请求作为输入示例化控制器类,并调用与其上的路由定义匹配的方法。
由于每个请求都由控制器类的一个单独示例处理,因此不可能共享示例变量。这也不是您实际上想要做的事情-隔离地处理每个请求可以减少出错的可能性。
相反,在Rails中通常使用
before_action
来定义一个回调来设置示例变量: