Rails如何返回object / true或false并重定向错误

时间:2015-07-05 23:40:31

标签: ruby-on-rails ruby

在设计rails应用程序时,我经常遇到需要调用返回true的函数或返回错误消息的原因。我已经看到很多方法可以做到这一点,但我很好奇什么是好方法。以下是我可能会使用的几个例子以及它们的优点和缺点。请回答你认为好的方法和原因?

# PROS:
# not returning multiple objects
# syntax looks good with if !valid
# uses activerecord style errors
# not interupting program with Exceptions
#
# CONS:
# must know path in advance
# could be sending many errors
#
if (!object.validate_something)
  respond_to |format|
    format.html redirect_to place_to_redirect_to_path, notice:/alert: object.errors.full_messages, status: :some_status_code
    format.json render json: { error: object.errors }, status: :some_status_code, location: place_to_redirect_to_path
  end
end

# PROS:
# dynamic redirect path
# not interupting program with Exceptions
# guarenteed single error if desirable
#
# CONS:
# returning multiple objects
#
path, error = object.validate_something
if (error)
  respond_to |format|
    format.html redirect_to path, notice:/alert: error, status: :some_status_code
    format.json render json: { error: error }, status: :some_status_code, location: path
  end
end

# PROS:
# uses activerecord style errors
#
# CONS:
# not very readable
# returns object or false
# must know path
#
if (response = validate_something)
  # do something with response
else
  respond_to |format|
    format.html redirect_to place_to_redirect_to_path, notice:/alert: object.errors.full_messages, status: :some_status_code
    format.json render json: { error: object.errors }, status: :some_status_code, location: place_to_redirect_to_path
  end
end

这是一篇类似的帖子,但并没有完全回答问题Returning true or error message in Ruby

0 个答案:

没有答案