Rails如何计算操作的响应代码

时间:2013-07-13 08:50:51

标签: ruby-on-rails

Rails如何计算控制器操作的响应代码?

给出以下控制器操作:

def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: 'show' }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

(我使用相同的视图来显示和编辑记录)

通过这个积极的测试:

test "should update basic user information" do
  user = users(:jon)
  user.first_name="Jonas"
  put :update, :id => user.id, :merchant_user =>user.attributes
  assert_response :found
  user = Merchant::User.find(user.id)
  assert user.first_name == "Jonas", "Should update basic user information"
end

负面测试是这样的:

test "should not update user email for an existing email" do
  user = users(:jon)
  original_user_email = user.email
  existing_user_email = users(:doe)
  user.email=existing_user_email.email
  put :update, :id => user.id, :merchant_user =>user.attributes
  assert_response :success
  user = Merchant::User.find(user.id)
  assert user.email == original_user_email, "Should not update email for an exising one"
end

成功更新记录会产生302响应代码,我认为对于GET资源/:ID,rails默认为302。无法更新记录会导致200 OK。

如何计算这些响应代码以及如何覆盖它们?

由于

2 个答案:

答案 0 :(得分:5)

见下面的内联评论

if @user.update(user_params)
  format.html { redirect_to @user, notice: 'User was successfully updated.' }
  # 302, the save was successful but now redirecting to the show page for updated user
  # The redirection happens as a “302 Found” header unless otherwise specified.

  format.json { head :no_content }
  # 204, successful update, but don't send any data back via json

else
  format.html { render action: 'show' }
  # 200, standard HTTP success, note this is a browser call that renders 
  # the form again where you would show validation errors to the user

  format.json { render json: @user.errors, status: :unprocessable_entity }
  # 422, http 'Unprocessable Entity', validation errors exist, sends back the validation errors in json

end

如果查看format.json { render json: @user.errors, status: :unprocessable_entity },它会使用status上的render选项明确HTTP状态代码 因此,如果您愿意(可能不这样做),您可以render action: 'show', status: 422render action: 'show', status: :unprocessable_entity - 并将默认值设为200 Ok(rails使用符号:success来设置:ok 1}}以及

另见:

Getting access to :not_found, :internal_server_error etc. in Rails 3 在您的控制台Rack::Utils::HTTP_STATUS_CODES中查看所有状态代码(值为轨道中的符号),即Unprocessable Entity:unprocessable_entity

答案 1 :(得分:1)

  1. 我非常怀疑您的代码是否有效,因为您在控制器中使用update而不是update_attributesupdate是ActiveRecord :: Callback中的私有方法,不能公开使用。 感谢Michael的评论指出update是Rails中update_attributes的替代4,虽然没有提到问题。

  2. 测试响应是不必要的,打破传统的响应代码更加不必要。相反,请检查对ActiveRecord以及响应正文或路径所采取的效果。