2016-11-10 65 views
1

我想改善我的代码在控制器根据DRY。DRY在控制器

def create 
    blog.user = current_user 
    blog.save 
    respond_with blog, location: user_root_path 
    end 

    def update 
    blog.update(blog_params) 
    respond_with blog, location: user_root_path 
    end 

    def destroy 
    blog.destroy 
    respond_with blog, location: user_root_path 
    end 

每种方法都有一个respond_with博客,位置:user_root_path。我怎样才能隐藏它?

回答

2

你可以做一个:after_action过滤

之后的动作完成后,过滤器运行。它可以修改响应。大多数情况下,如果在后置过滤器中完成某项操作,则可以在操作本身中完成,但如果在运行任何一组操作后要运行某个逻辑,则后置过滤器是一个很好的地方它。

:after_action :responding, only: [:create, :update, :destroy] 

def create 
    blog.user = current_user 
    blog.save 
end 

def update 
    blog.update(blog_params) 
end 

def destroy 
    blog.destroy 
end 

def :responding 
    respond_with blog, location: user_root_path 
end