2015-01-21 77 views
0

如果我有以下編輯方法:在更新方法在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 update 
    edit 
    if @pet.update_attributes(pet_params) 
    redirect_to(:action => 'show', :id => @pet.id) 
    else 
    render('index') 
    end 
end 

回答

0

控制器操作不應該調用其他操作。如果兩者之間(如@pet = Pet.find(params[:id])這可以通過before_action進行重疊:

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 

http://guides.rubyonrails.org/action_controller_overview.html#filters