Custom Get with elements behind ID
Hi, i've got an API which uses functions behind IDs in it's path (actually, it's the PuppetDB API). So, valid requests look like GET /v2/nodes/foo.bar.com/facts (where foo.bar.com is the id)
Now, I already did a bit reseach and found issue #119 here, and defined a custom get:
class Node
include Her::Model
collection_path "/v2/nodes"
def facts(params = {})
self.class.get("#{self.id}/facts", params)
end
end
Calling it with Node.find('foo.bar.com').facts unfortunately fires two GETs to the API Endpoint: GET /v2/nodes/nixwissen.erlm.siemens.de HTTP/1.1 GET /facts HTTP/1.1 which of course doesn't work. Any idea to get this working without defining completely custom get's ?( Node.get(":collection_path/:id/facts").
Thanks in advance! Björn
Have you tried using associations?
class Node
include Her::Model
collection_path "/v2/nodes"
has_many :facts
end
Node.find('foo.bar.com').facts
# GET /v2/nodes/foo.bar.com/facts
Hi, just tested that: Added has_many :facts to the node model. There already was a fact model defined ( for another endpoint of that api) which looks like this: class Fact include Her::Model collection_path "/v2/facts" end
Unfortunately, calling Node.find('foo.bar.com').facts still fires (only) a GET /v2/nodes/foo.bar.com HTTP/1.1 This returns some valid json stuff, but just basic information about the node, not the facts.
It’s normal that Node.find('foo.bar.com').facts calls GET /v2/nodes/foo.bar.com (because of the find) but it should also call GET /v2/nodes/foo.bar.com/facts because of the association.
Can you try Node.find('foo.bar.com').facts.inspect which will certainly fetch the data (because calling #facts doesn’t actually fetch the data, it just returns a relation that will be called if you call a method on it (like #each, #inspect or #to_a).
Tried that already, but it doesn't fetch annything more:
Loading development environment (Rails 3.2.13) 2.0.0-p247 :001 > mytest = Node.find('foo.bar.com').facts.inspect => "#<Her::Model::Associations::HasManyAssociation:0x00000003f3dd08 @parent=#<Node(/v2/nodes) name="foo.bar.com" deactivated=nil catalog_timest amp="2013-07-12T13:58:23.823Z" facts_timestamp="2013-07-12T13:58:23.311Z" report_timestamp=nil>, @opts={:class_name=>"Fact", :name=>:facts, :data_key=>:facts, :default=>[], :path=>"/facts", :inverse_of=>nil}, @params={}, @klass=Fact , @name=:facts>"
Only one GET fired: GET /v2/nodes/nixwissen.erlm.siemens.de HTTP/1.1
Hmm ,strange :)
ah got it :) .inspect doesn't work, but looping it with .each finally throws the correct request ! :) Thanks a LOT for your help!!!!