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
为什么我的对象不存在?
感谢
答案 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
这似乎是一个可能的起点。