Reputation: 3048
I want to pass a variable from a Rails controller to a JavaScript file. I found some solutions and now I have:
# controller
def index
@coords = Map.all
end
#view
<%= content_tag 'div', id: 'coords', data: {coords: @coords } do %>
<% end %>
#javascript
alert($('#coords').data(coords));
$('#coords').data(coords)
returns an object Object
.
How do I access a particular attribute of coords
such as coord.lat
etc. in javascript? Also, do @coords
get converted to JSON
automatically?
NOTE: I couldn't use gon
gem. I think it is not supported in rails 4.2. So I need a solution without gems.
Upvotes: 1
Views: 1540
Reputation: 1861
Here how I use gem gon
with rails-4.2.0. Nothing special really:
# Gemfile.lock where rails binded to version 4.2.0
gon (5.2.3)
actionpack (>= 2.3.0)
json
multi_json
request_store (>= 1.0.5)
....
PATH
remote: engines/mobile_api
specs:
mobile_api (0.1)
itunes-receipt
rails (~> 4.2.0)
# Gemfile
source 'http://rubygems.org'
gem 'rails', '4.2.0'
gem 'gon'
# layout main.html.slim
doctype html
html
head
meta charset="utf-8"
= include_gon
# main_controller.rb (In the controller)
class MainController < ApplicationBaseController
before_action :start_marketing_split_test
layout 'main'
# ... actions here
def start_marketing_split_test
split_test_name = 'ab_test_1'
alternatives_loader =
Marketing::AB::AlternativesLoader.new(split_test_name)
alternative = ab_test(split_test_name,
alternatives_loader.alternatives)
gon.push({"#{split_test_name}" => JSON.parse(alternative)})
end
============================
But if you need solution without gon
you can pass variables right in you backend templates:
For example:
# layouts/application.html.slim
doctype html
html
head
meta charset="utf-8"
title
body
javascript:
window.app_options = {
'flash_alert': "#{raw(flash[:alert])}",
'flash_warning': "#{raw(flash[:warning])}",
'flash_notice': "#{raw(flash[:notice])}",
'current_user_id': "#{current_user.try(:id)}",
'current_user_phone': "#{current_user.try(:phone)}"
};
Upvotes: 2
Reputation: 1944
When retrieving data attribute values with jQuery .data(key)
, the key
you use should be a String
. And yeah data: { coords: @coords}
converts @coords
to JSON string automatically. So I think it should work for you if you call it like this :
$('#coords').data('coords');
# Returns array of JavaScript coord objects.
$('#coords').data('coords')[0].id;
# Returns first coord's id.
Upvotes: 1
Reputation: 530
You can use in view file
<%= javascript_tag do %>
var1 = @coords.lat
var2 = @coords.lgt
<% end %>
then you can access var1 and var2 through javascript code.
Upvotes: -1
Reputation: 2541
what about using a helper method like following
<%= content_tag 'div', id: 'coords', data: <%= json_for @coords%> do %>
module ApplicationHelper
def json_for(target_model)
target_model.to_json #generates a json object
end
end
https://github.com/rails-api/active_model_serializers
Upvotes: 0