Search code examples
ruby-on-railsactiverecordactiveresource

Ruby on Rails ActiveResource not working


I am new to RoR and I am trying to build simple web application that uses ActiveResource ActiveRecord

I have one simple rails project hosted on localhost:3001. The application has welcome controller that looks like this

class WelcomeController < ApplicationController
  def index
    @persons = []
    num = 0
    until num < 10 do
      @persons[num] = Person.new
      @persons[num].name = [*('A'..'Z')].sample(8).join
      @persons[num].surname = [*('A'..'Z')].sample(64).join 
      @persons[num].dob = Time.at(rand * Time.now.to_i)      
      num+1      
    end

    respond_to do |format|
      format.xml { render :xml => @persons}
    end
  end
end

Person class looks like this:

class Person
  attr_accessor :name, :surname, :dob
end

This rails application should use as REST service for other application hosted on localhost:3000

The model in letter application looks like this:

class Person < ActiveResource::Base
   self.site = "http://localhost:3001"
end

Now, my question is how to list all 10 persons on the view?

I have tried to use Person model as ActiveResource, in person controller:

class PersonController < ApplicationController
  def index
   @persons= Person.find(":all")   
  end
end

by I get message ActiveResource::ResourceNotFound in PersonController#index

Thanks in advance.


Solution

  • First of all, I'm not sure why you're trying to create 10 People in your WelcomeController, but here's a better way.

    class WelcomeController < ApplicationController
      def index
        10.times do
          person = Person.new
          person.name = [*('A'..'Z')].sample(8).join
          person.surname = [*('A'..'Z')].sample(64).join
          person.dob = Time.at(rand * Time.now.to_i) 
          person.save # This part is necessary for data to persist between requests
        end
    
        @persons = Person.all
    
        respond_to do |format|
          format.xml { render :xml => @persons}
        end
      end
    end
    

    Then, of course in your PersonController you can use

    @persons = Person.all
    

    or

    @persons = Person.find(:all)