Ruby on rails 在Rails的更新方法中使用编辑方法
如果我有以下编辑方法:Ruby on rails 在Rails的更新方法中使用编辑方法,ruby-on-rails,Ruby On Rails,如果我有以下编辑方法: def edit @pet = Pet.find(params[:id]) end 以及以下更新方法: def update @pet = Pet.find(params[:id]) if @pet.update_attributes(pet_params) redirect_to(:action => 'show', :id => @pet.id) else render('index') end end 我是否可以简
def edit
@pet = Pet.find(params[:id])
end
以及以下更新方法:
def update
@pet = Pet.find(params[:id])
if @pet.update_attributes(pet_params)
redirect_to(:action => 'show', :id => @pet.id)
else
render('index')
end
end
我是否可以简单地在update方法中使用edit方法,如中所示:
def update
edit
if @pet.update_attributes(pet_params)
redirect_to(:action => 'show', :id => @pet.id)
else
render('index')
end
end
控制器操作不应调用其他操作。如果这两个参数之间存在重叠,例如@pet=pet.findparams[:id],则可以通过before_操作完成:
class PetsController < ApplicationController
before_action :set_pet, only: %i[edit update]
def edit
end
def update
if @pet.update_attributes(pet_params)
redirect_to(:action => 'show', :id => @pet.id)
else
render('index')
end
end
private
def set_pet
@pet = Pet.find(params[:id])
end
end