Search code examples
ruby-on-railsrubyactiveresource

Read records from database using Active Resource


I have written the following code snippet to read data from the database :

    require 'rubygems'
    require 'active_resource'

    class Website < ActiveResource::Base
      self.site = "http://localhost:3000"
    end

    websites = Website.find(:all)
    puts websites.inspect

this gives me following output :

prompt:~/Desktop$ ruby active_resource_example.rb
=> nil

My websites table contains the following fields :

    == Schema Information

 Table name: websites

  id          :integer(4)      not null, primary key
  name        :string(255)
  url         :string(255)
  description :text
  active      :boolean(1)      default(TRUE)
  created_at  :datetime
  updated_at  :datetime

There are records present in my websites table, but why it is showing me nil result. This is the simplest code I could write and still not getting the required result.

Can anyone help me with this?


Solution

  • First of all, you should start web server through call rails server command. I think you already prepared this because in the opposite case you received some errors about connection. Later, you must be sure that your routes contains something like this:

    resources :websites
    

    and your website controller contains format.json section in respond_to block. At last you can check logs - after preparing Website.find(:all) call (to the point - you can use Website.all) you should receive following record:

    Started GET "/websites.json" for ....