I have a collection, want to generate a javascript object with it
I have a collection:
@products = Product.where("product_type = ?", 3)
开发者_如何学JAVAI now want to create a javascript object so I can perform lookups in the UI like:
my_products[2342]
and it will return:
"some_name"
I believe it should look like:
var my_products = {
2342: "some_name",
5321: "there blah"
}
What's a nice way to generate this in my controller's action?
ActiveRecord and Ruby in general has a method to_json
that should help you do what you're looking for.
Basically construct the array you want to create in Ruby and call to_json
to create a string that is a valid javascript object to use.
I recommend using to_json, but if you want another option you could generate the js object literal notation using an js.erb template.
views/products/products.js.erb
var products = {
<% @products.each do |product| %>
<%= "#{product.id}: \"#{@product.name}\"," %>
<% end %>
}
Then, setup a controller method using either a dedicated method or a responds_to block. Finally, have the AJAX call the method and execute the returned code which will result in you having access to the product variable defined in the js.erb template.
精彩评论