I am using Rails 3. I just want to create a simple javascript object from my controller. I don't want to render js because I'm already rendering html page and I want that javascript object in that html page.
1 Answer
You want to make data from the controller available in javascript? Then you should use JSON. You can convert any ruby datatype into a json object with the .to_json
Since JSON is valid javascript you can do
var json_object = <%= @ruby_data.to_json %>;
3 Comments
Sharjeel
what's the syntax if I for example I want to make @company available? I know I can do @company.to_json but that's not enough.
jordelver
Is @company an ActiveRecord object? If so, it should work out of the box.
Tarscher
it's indeed an ActiveRecord object. Conversion works out of the box