Reputation: 2070
I retrieve database record in ruby on rails just like this:
@amenities = AmenitiesAndFeatures.where(is_amenities: true).order("name ASC")
In my javascript, I want to query on the records that was inside my @amenities. It this possible.
var x = 1
var amenity = <%@amenities.select("name").where(id: x)%>
Is this possible? If not, what are the ways to do this? I need to process on the active record retrieve from the database. I do not want to requery again or use ajax just to pull again the data that is already in my @amenities. Thanks!
Upvotes: 0
Views: 88
Reputation: 79
Maybe you can send your amenities to view in json format and use hidden_field to store your data like this.
#controller
@amenities = AmenitiesAndFeatures.where(is_amenities: true).order("name ASC")
@amenities_json = @amenities.map {|amenity| {id: amenity.id, name: amenity.name} }.to_json
#view
<%= hidden_field_tag "amenities_json", @amenities_json %>
#javascript
var amenities = JSON.parse($("#amenities_json")[0].value);
Upvotes: 1
Reputation: 6692
You can put the data you need to the page one time with json format, you can define as many variables as you want.
in your controller:
@amenities = AmenitiesAndFeatures.where(is_amenities: true).order("name ASC")
@amenities_json = @amenities.to_json
in your page:
var amenities = <%= @amenities_json.html_safe %>;
$.each(amenities, function(index, amenity){
alert(amenity.name);
});
Upvotes: 1