0

I'm trying to parse a hash to json but in the index.json.jbuilder I get empty hash.

what am I doing wrong:

  def self.fake_objects 

    fake_objects = {id: 1,
                  title: 'appointment one',
                  description: 'bla bla bla',
                  start_time: '2014-08-19 14:00:00.000000000 Z',
                  end_time: '2014-08-19 14:30:00.000000000 Z'}  
  end 

events_controller

  def index
    @events = Event.all
    @fake_objects = Event.fake_objects 
  end

index.json.jbuilder

(@fake_objects).to_json do |event|
  json.extract! event, :id, :title, :description
  json.start event.start_time
  json.end event.end_time
  json.url event_url(event, format: :html)
end

class Event < ActiveRecord::Base
  def self.fake_objects 
    fake_objects = Event.new(id: 1,
                  title: 'appointment one',
                  description: 'bla bla bla',
                  start_time: '2014-08-19 14:00:00.000000000 Z',
                  end_time: '2014-08-19 14:30:00.000000000 Z')
  end 
end
4
  • @fake_objects is likely nil in your view. You don't set it in the controller. Commented Aug 25, 2014 at 12:17
  • @evanx You have defined fake_objects but you are using @fake_objects check once Commented Aug 25, 2014 at 12:24
  • @SergioTulentsev I just omitted the controller part, I edited the post. Commented Aug 25, 2014 at 12:42
  • does not to_json apply to ActiveRecord::Base objects ? Commented Aug 25, 2014 at 12:55

1 Answer 1

-1

try something like:

json.events @fake_objects do |json, event|
  json.extract! event, :id, :title, :description
  json.start event.start_time
  json.end event.end_time
  json.url event_url(event, format: :html)
end

but @fake_objects should be defined as [], for single event you could write:

json.event do |json|
  json.extract! @fake_object, :id, :title, :description
  json.start @fake_object.start_time
  json.end @fake_object.end_time
  json.url event_url(@fake_object, format: :html)
end

If you need just array of results (without events: []) write json.array! ..

Sign up to request clarification or add additional context in comments.

3 Comments

I when I use json array like json.array!(@fake_objects) I get: undefined method `id' for [:id, 1]:Array
it looks like your @fake_objects is not Array, but Hash
If you want render single Hash item you could use second variant (even without json.event ..) but instead of @fake_object.id wirte @fake_object[:id]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.