我有一个叫做用户的模型,我想用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