Rails,重构控制器

时间:2012-10-20 06:33:25

标签: ruby-on-rails ruby refactoring

你可以帮我重构和干吗?我没有想法。感谢。

if request.xhr?
  render :json => {
    :status => true,
    :location => root_url + "/projects",
    :message => I18n.t("project.destroy")
  }
else
  flash[:notice] = I18n.t("project.destroy")
  redirect_to :action => :index
end

2 个答案:

答案 0 :(得分:1)

你无能为力,但

message = I18n.t('project.destroy')

return render :json => {
         :status => true,
         :location => "#{root_url}/projects",
         :message => message
       } if request.xhr?

flash[:notice] = message
redirect_to :action => :index

答案 1 :(得分:1)

好吧,你可以像这样覆盖application_controller.rb中的redirect_to

def redirect_to(options={}, response_status={})
  if request.xhr?
    render :json => { :status => true, :location => options, :message => flash[:notice] }
  else
    super
  end
end

然后继续使用

flash[:notice] = I18n.t('project.destroy')
redirect_to projects_path

在您的控制器中。