如何让这个Ruby方法更漂亮?

时间:2013-08-04 15:39:39

标签: ruby-on-rails ruby

我相信条件可以写得更好:

def update
  if allow_update?
    if @company.update_attributes(params[:company])
      flash.now[:success] = "success message"
    else
      flash.now[:error] = "error message"
    end
  else
    flash.now[:error] = "error message"
  end

  render :show
end

我该如何重写?

2 个答案:

答案 0 :(得分:10)

使用&&运算符,可以将两个if合并为一个:

def update
  if allow_update? && @company.update_attributes(params[:company])
    flash.now[:success] = "success message"
  else
    flash.now[:error] = "error message"
  end

  render :show
end

答案 1 :(得分:0)

您可以使用一些字符串插值和三元运算符来缩短代码。

def update
  allow_update? && @company.update_attributes(params[:company]) ? result = "success" : 
  result = "error"
  flash.now[result.to_sym] = "#{result} messege"
  render :show
end
相关问题