Falcon
Falcon

Reputation: 1463

Parse ruby object in JavaScript (Rails)

in my view i have one object, and want to work with this onject from javascript i try to

  var js_obj  = jQuery.parseJSON('<%=raw @rails_obj.to_json %>');

it works. but if i have "'" symbols, new string symbols, ,,, in this object all fails.

Have somebody know good approach to do it?

Upvotes: 10

Views: 9617

Answers (4)

cyberfly
cyberfly

Reputation: 5848

Rails 5.X

controller

def new
      @organization_json = Organization.first().to_json
end

view

<script>
    var organization_json = <%= @organization_json.html_safe %>;
<script>

Upvotes: 0

Gerson Azevedo
Gerson Azevedo

Reputation: 111

I find this to be the best way. Worked everytime

 <%= javascript_tag "var obj = #{@obj.to_json}" %>

Upvotes: 3

iain
iain

Reputation: 16274

JSON is valid Javascript right out of the box, so why not just do:

var js_obj = <%= @rails_obj.to_json %>;

Upvotes: 14

jwueller
jwueller

Reputation: 30996

You need to escape all single-quotes then. ActionView has a helper for escaping JavaScript: ActionView::Helpers::JavaScriptHelper#escape_javascript

Upvotes: 2

Related Questions