1

我的“entries_controller.rb”中有以下代码

 def update
     @entry = Entry.find(params[:id])
     puts "received HTTP request to update old entry:#{@entry.inspect} with"
     puts "new parameters: #{params}"
     if @entry.update_attributes(params[:entry])
       puts"Update was successful"
       @entry2 = Entry.find(params[:id])
       puts "Here is the new value #{@entry2.inspect}"
     end
  end

当我从客户端向服务器发送 put 请求时,我的控制台会显示:

  2013-02-17T20:12:25+00:00 app[web.1]: received HTTP request to update old 
  entry:#<Entry id: 1, created_at: "2013-02-17 19:17:40", updated_at: "2013-02-17 19:17:40", 
  description: "Test", title: "Home", category: "-1", latitude: "49.258061", longitude: "-123.153972", hasPhoto: false> with

  2013-02-17T20:12:25+00:00 app[web.1]: new parameters: {"description"=>"Test", "id"=>"1", "category"=>"-1", "hasPhoto"=>"0", "latitude"=>"49.258061", "longitude"=>"-123.153972", 
  "title"=>"Updated home", "action"=>"update", "controller"=>"entries", "format"=>"json"}

  2013-02-17T20:12:25+00:00 app[web.1]: Update was successful

  2013-02-17T20:12:25+00:00 app[web.1]: Here is the new value #<Entry id: 1, created_at: "2013-02-17 19:17:40", updated_at: "2013-02-17 19:17:40", description: "Test", 
  title: "Home", category: "-1", latitude: "49.258061", longitude: "-123.153972", hasPhoto: false>

如您所见,旧记录并未真正更新。即使 if 子句被评估为真。查看“title”的值没有从“Home”更改为“Updated Home”。

我想知道这是什么错误?它说它更新了,但它并没有真正更新。

有人可以帮我理解这一点吗?

谢谢

4

1 回答 1

2

发生的事情是在您的视图文件中,您没有在视图中设置适当的表单。您的参数正在返回

{"description"=>"Test", "id"=>"1", "category"=>"-1", "hasPhoto"=>"0", "latitude"=>"49.258061", "longitude"=>"-123.153972", 
  "title"=>"Updated home", "action"=>"update", "controller"=>"entries", "format"=>"json"}

当实际上他们应该像这样返回时......

{"entry" => {"description"=>"Test", "id"=>"1", "category"=>"-1", "hasPhoto"=>"0", "latitude"=>"49.258061", "longitude"=>"-123.153972", 
  "title"=>"Updated home"}, "action"=>"update", "controller"=>"entries", "format"=>"json"}

注意到区别了吗?您有关条目的参数被包装并附加到属性条目。这样,当 Rails 查看您的参数时,它就知道哪些参数适用于您新更新的条目。如果不查看您的表单,就无法告诉您如何专门修复它,但这是一个很好的起点

于 2013-02-17T20:58:03.417 回答