DZone 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
# 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 }
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.




