ActiveResource .create没有错误,但没有持久化

时间:2011-11-23 00:17:10

标签: ruby-on-rails activeresource

require 'active_resource'

class MyRsrc < ActiveResource::Base
    self.site = "http://localhost:9292/api/0/category/sys_demo"
    self.element_name = "myname"
end


# from https://github.com/anibalcucco/basecamp-wrapper/issues/11
class Hash
  def collect!(&block)
    ret = []
    self.each {|key,val|
      if val.kind_of? Array
        val.collect!{|subval|
          block.call subval
        }
        ret = val
      end
    }
    return ret
  end
end


r = MyRsrc.create(node_uri: 'http://api.example.com/api/nodes/4')
 => #<MyRsrc:0x000000033a13f0 @attributes={"node"=>"http://api.example.com/api/nodes/4", "id"=>"42"}, @prefix_options={}, @persisted=false, @remote_errors=nil, @validation_context=nil, @errors=#<ActiveResource::Errors:0x0000000339a050 @base=#<MyRsrc:0x000000033a13f0 ...>, @messages={}>> 

r.errors.count
 => 0 

r.errors.full_messages
 => [] 

r.valid?
 => true 

r.new?
 => true 

r.persisted?
 => false 

r.save
 => true 

r.persisted?
 => false 

为什么我的对象不存在?

感谢

1 个答案:

答案 0 :(得分:3)

服务器返回的响应是什么? create具有以下定义:

def create
  connection.post(collection_path, encode, self.class.headers).tap do |response|
    self.id = id_from_response(response)
    load_attributes_from_response(response)
  end
end

load_attributes_from_response定义为:

def load_attributes_from_response(response)
  if (response_code_allows_body?(response.code) &&
      (response['Content-Length'].nil? || response['Content-Length'] != "0") &&
      !response.body.nil? && response.body.strip.size > 0)
    load(self.class.format.decode(response.body), true)
    @persisted = true
  end
end

因此,如果符合以下条件,您的资源将不会设置persisted

  1. 响应代码表示无体反应
  2. 响应的内容长度不存在或0
  3. 响应正文为空
  4. 这似乎是一个可能的起点。