开发者

Create a JSON representation of a non-ActiveRecord model

I'm trying to create a model in a Rails 3.1rc4 application that is not based on ActiveRecord.

class Database
  attr_r开发者_如何学编程eader :name

  def initialize(connection, database_name)
    @connection = connection
    @name = database_name
  end

  def self.all
    connection = Mongo::Connection.new("localhost")
    connection.database_names.map { |db_name| new(connection, db_name) }.sort { |x, y| x.name <=> y.name }
  end
end

I want to be able to render this a JSON in a _list.html.erb template as follows

<script>
  var databases = <%= @databases.as_json %>
</script>

The method in the application controller is as follows

def populate_databases
  @databases = Database.all
end

I am trying to represent the collection of all of the database JSON to be processed by Backbone.js. However, I cannot seem to figure out the appropriate way to do this. The code above almost works, but the double-quotes in the results are encoded as &quot;. Also, I would like to be able to only include the @name property and not the @connection property. Can someone please help me determine the appropriate way of coding this?


This:

var databases = <%= @databases.as_json %>

Is automatically encoding @databases.as_json for use in HTML, that's why your double quotes are being converted to &quot;. Try using escape_javascript instead:

var databases = <%= escape_javascript @databases.to_json %>

Also, as_json returns a data structure that is ready for conversion to JSON, to_json returns the actual JSON string so you might want to fix that up while you're at it; for example:

ruby-1.9.2-p0 > {:a => 'a'}.as_json
 => {"a"=>"a"} 
ruby-1.9.2-p0 > {:a => 'a'}.to_json
 => "{\"a\":\"a\"}" 


I was able to solve the problem implementing a variation of this answer: rails - how to render a JSON object in a view

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜