Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Accessing ActiveRecord objects in javascript (See related posts)

   1  
   2  # put this in lib/active_record/json.rb
   3  require 'json/lexer'
   4  require 'json/objects'
   5  module ActiveRecord
   6    module Json # :nodoc:
   7      DEFAULT_CONVERSIONS = { Time => [:to_s, :db] }
   8      def to_json(conversions = {})
   9        conversions = DEFAULT_CONVERSIONS.merge(conversions)
  10        self.attributes.keys.inject({}) do |hsh, key|
  11          value = self.send(key)
  12          hsh.merge(key => conversions[value.class] ? value.send(*conversions[value.class]) : value.to_s)
  13        end.to_json
  14      end
  15    end
  16  end
  17   
  18  # in environment.rb do
  19  #require "#{RAILS_ROOT}/lib/active_record/json"
  20  #ActiveRecord::Base.class_eval { include ActiveRecord::Json }


Doing something like
   1  <%= 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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5828 code snippets

Related Posts