Over a million developers have joined DZone.

Accessing ActiveRecord Objects In Javascript

DZone's Guide to

Accessing ActiveRecord Objects In Javascript

Free Resource

# put this in lib/active_record/json.rb
require 'json/lexer'
require 'json/objects'
module ActiveRecord
  module Json # :nodoc:
    DEFAULT_CONVERSIONS = { Time => [:to_s, :db] }
    def to_json(conversions = {})
      conversions = DEFAULT_CONVERSIONS.merge(conversions)
      self.attributes.keys.inject({}) do |hsh, key|
        value = self.send(key)
        hsh.merge(key => conversions[value.class] ? value.send(*conversions[value.class]) : value.to_s)
# in environment.rb do
#require "#{RAILS_ROOT}/lib/active_record/json"
#ActiveRecord::Base.class_eval { include ActiveRecord::Json }

Doing something like <%= var post = @post.to_json %> in a javascript snippet should allow you to use the basic AR attributes such as post.title, post.summary (using the Weblog analogy).  You could also pass the json bits to a javascript function.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}