我有一個叫做用戶的模型,我想用API來更新。我認爲這樣做的方式是創建一個更新路由並插入執行更新的代碼。我創建了一個使用RSpec的測試,它似乎工作,但是,我想實際上看到我的數據庫中更改的數據,所以我試圖使用curl來更新我的開發數據庫。使用curl來測試Rails路線
我試着命令
curl -X PUT -d "attribute1 = value1, attribute2 = value2" http://localhost:3000/users/1
,但我得到一個錯誤
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
.
.
.
</style>
</head>
<body>
<h1>
NoMethodError
in UsersController#update
</h1>
<pre>You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]</pre>
.
.
.
繼承人是在routes.rb中的相關行
resources :users, :only => [:create, :update, :destroy]
下面是相關的代碼在控制器
def update
@user = User.find(params[:id])
if params[:user][:attribute1] == ("x" || "y" || "z")
params[:user][:attribute3] = Time.now
end
@user.update_attributes(:user)
render :nothing => true
end
最後這裏的規範代碼,通過
describe "PUT 'update'" do
before(:each) do
@user = Factory(:user)
end
describe "success" do
it "should be successful" do
put :update, :id => @user, :user => { :attribute1 => "x", :attribute2 => "xyz"}
response.should be_success
end
it "should update attribute" do
old_attribute = @user.attribute3
put :update, :id => @user, :user => { :attribute1 => "x", :attribute2 => "xyz"}
@user.attribute3 != old_attribute
end
end
end
我試圖找到一個很好的捲曲教程來檢查我的語法,但我只能找到的例子,所以我也不太清楚,如果語法是正確的。
謝謝,剛剛嘗試過,我得到相同的錯誤 – ageorgie 2011-06-06 19:21:32
對不起 - 我只是看看你的控制器代碼。既然你有'params [:user] [:attribute1]''等你的屬性實際上需要封裝在用戶[...]。請看我最新的回覆。 – 2011-06-06 19:27:26