hawmack13
hawmack13

Reputation: 233

Ruby on Rails: how to pass JSON to JavaScript

I have a JavaScript snippet in my Ruby on Rails application that talks to a remote server and passes it a JSON composed of an array of dictionaries containing things like SKU, price, etc.

It's simple to generate in Ruby:

@items = @order.line_items.map do |item|
  {
    sku: item.variant.sku,
    price: item.variant.price
    quantity: item.quantity
    currency: current_user.currency
  }
end

However, when I insert it in JavaScript -- it doesn't work.

{        
  items: "<%= @items %>"
}

The problem I think is that the entities are escaped. If I use alert to inspect the returned value, I can see all the entities like quotation marks are escaped.

Other places where I interpolate values directly seem to work fine. For example:

invoice_number: "<%= @order.id %>"

Others have had this problem, but none of the solutions appear to work in this case. I've tried raw, html_safe, etc.

I must be missing something. What is the best way to solve this problem?

Upvotes: 1

Views: 1236

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

There are three problems.

First, you don't need "" around <%= @items %>.

Second, <%= @items %> inserts @items.to_s, but {"key" => 12}.to_s equals '{"key"=>12}', which is not a valid JSON.

Third, you need html_safe to make Rails to not escape special characters.

You get:

items: <%= @items.to_json.html_safe %>

Upvotes: 1

Related Questions