Friday, March 9, 2012

Rails JSON mapping

Rails to_json is great when you are using web service to talk to your own application. But sometimes when you expose service for some third party application, then you need to export you own data in their format. In my can I had to expose my data to be able to use fullcalendar. And fullcalendar expects data in their format. So thanks to the discussion here, I found a way to represent your in the following way,

  def story_feed
    @stories = @project.stories
    render :json => @stories.map { |story| 
      { :id => story.id,
        :title => story.title,
        :start => story.start_at || Date.today,
        :end => story.complete_at || Date.today }
    }
  end

2 comments:

Unknown said...

What about perfomance? Can't you use pluck or as_json instead of initializing so many record objects?

Jitu said...

I have not tested the performance. It was written in 2012. Now the solution might be a bit different. This does not initialize AR objects. These are basic dictionaries, which picks part of the objects to only expose properties that are needed.