ere
ere

Reputation: 1779

json to active record

I'm a bit confused, how can I take a restful JSON resource and access it as if it was a local active record using active resource? I find lots of tutorials circa 2008 but nothing that looks very recent.

I currently have something like:

def freebase_list

  connection = Faraday.new 'https://www.googleapis.com/freebase/v1' do |conn|

    conn.adapter Faraday.default_adapter
    conn.use FaradayMiddleware::ParseJson
    #conn.use Faraday::Response::Mashify
  end

  response = connection.get do |req|
    req.url('search', :query => self.title, :limit => 10)#, :filter => '(any namespace:/wikipedia/en_id namespace:/authority/imdb/title)')
  end

  if response.body && response.body["result"]
    response.body["result"].delete_if {|x| x["notable"].nil? }
    response.body["result"].delete_if {|x| x["score"] < 50 }
  end
end

def types
  result = []
  self.freebase_list.each do |r|
    result << { :name => r["notable"]["name"], :value => r["mid"] } if r["notable"]
  end
  return result
end

Could someone point me in the right direction, I feel like I'm almost there but not quite.

If I use active resource directly I get a return of nil:

class Freebase < ActiveResource::Base
    self.site = "https://www.googleapis.com/freebase/v1/search/"
    self.format = :json


    #https://www.googleapis.com/freebase/v1/search?query=nirvana
    #Freebase.find(:all, :params => { :query => 'monkey', :limit => 10 })
    #=> nil



end

Upvotes: 1

Views: 1154

Answers (1)

Gazler
Gazler

Reputation: 84140

There is a library for this built into rails called ActiveResource and it gives you similar functionality to ActiveRecord.

class User < ActiveResource::Base
  self.site = "http://url.com/"
end

Going by the new docs, JSON is the default format.

There is also a railscasts episode on it.

Upvotes: 2

Related Questions