更新操作在编辑方法中是否有示例变量?Ruby on Rails

nnvyjq4y  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(118)

更新操作在编辑方法中是否有示例变量?
我正在开发一个表单验证,并希望在不删除现有输入的情况下呈现编辑表单。然而,我在编辑表单中的示例变量没有得到任何结果。有什么方法可以保存示例变量吗?

def update 
  render ‘edit’ and return unless account.update(params)
end

def edit
  @name = Account.find(params[:id]
end
zf2sa74q

zf2sa74q1#

更新操作在编辑方法中是否有示例变量?
不,原因是:
1.你向edit发出一个请求,rails会创建一个控制器的示例(在这里你设置@name)
1.你提交表单,这是一个由Rails处理的新请求,它将创建一个你的控制器的(新)示例。
你可能会得到你想要的东西,就像这样:

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

但更规范的方法是在变量中保存一个帐户示例

@account = Account.find(params[:id])

并在视图中使用它(如form_for @account)。但这可能适合也可能不适合您的用例。

91zkwejq

91zkwejq2#

没有。

当你的Rails服务器收到一个请求时,路由器会尝试匹配一个路由和相应的控制器/动作组合。然后路由器将请求作为输入示例化控制器类,并调用与其上的路由定义匹配的方法。
由于每个请求都由控制器类的一个单独示例处理,因此不可能共享示例变量。这也不是您实际上想要做的事情-隔离地处理每个请求可以减少出错的可能性。
相反,在Rails中通常使用before_action来定义一个回调来设置示例变量:

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

相关问题