Rate this script:  I Love it  /   I Hate it

Accessing ActiveRecord objects in javascript


Code


# 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)
      end.to_json
    end
  end
end
 
# in environment.rb do
#require "#{RAILS_ROOT}/lib/active_record/json"
#ActiveRecord::Base.class_eval { include ActiveRecord::Json }
<%= var post = @post.to_json %>

 

 
Accessing ActiveRecord objects in javascript scripts | Accessing ActiveRecord objects in javascript snippet | Accessing ActiveRecord objects in javascript example | Accessing ActiveRecord objects in javascript tutorial | Accessing ActiveRecord objects in javascript code