Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140847

Rails passing variable to JavaScript

$
0
0

I'm trying to get values through a has_many :through relationship. Three main databases: people, locations (which has street address and other information), and the join table, years, on a date for when someone lived or worked at the location. The join table is manually created because of the date. Numerous years items can exist for a person (they moved and worked at different places over time).

As I understand it the flow is that the show.html.erb calls javascript/packs/olPeopleMap.js which then calls show_locations.json.jbuilder. How do I pass the person.id to jbuilder?

From views/people/show.html.erb (of course the page for a particular person which I hope to show details about the person including locations they were associated with).

<div id="map" class="map"></div>  
<%= javascript_pack_tag 'olPeopleMap' %>
<div>

From javascript/packs/olPeopleMap.js which of course doesn't know for which person this is.

new VectorImageLayer({
  title: 'Where lived and worked',
  imageRatio: 2,
  source: new VectorSource({
    url: '../people/show_locations', // Doesn't know which person I want
    format: new GeoJSON()
}),

Non working code because it doesn't know the person_id (the code may have other problems):

# …/show_locations.json.jbuilder,
json.type "FeatureCollection"
json.features @person.years do |year|
# Person has_many :locations, through: :years  
  json.type "Feature"    
  json.properties do
    json.set! "marker-color", "#C978F3" # will make this different for resto and resid a
     # json.title year.resto
    json.name year.full_name
  end
  json.geometry do
     json.type "Point"
     json.coordinates [year.location['longitude'], year.location['latitude']]
  end # json.geometry
end # features

In summary, how do I pass person.id to the jBuilder? Or am I going at this all wrong? Happy New Year!


Viewing all articles
Browse latest Browse all 140847

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>