2017-09-26 68 views
1

我試圖從location模型中獲取rider模型的數據,並將其傳遞給javascript部分,以便我可以標記每個車手的位置。如何從另一個模型訪問一個模型屬性以在Rails 5中傳遞JavaScript視圖部分?

我試圖問我關於我打算做什麼的正確問題,但沒有運氣。

這是我的rider.rb模型。

class Rider < ActiveRecord::Base 
    has_one :location, as: :profile 
end 

這裏是我的location.rb模型。

class Location < ActiveRecord::Base 
geocoded_by :address 
belongs_to :profile, polymorphic: true 
validates :profile, :latitude, :longitude, presence: true 
end 

這是我的controllers.rb

def show 
    @riders = Rider.all 
end 

這裏是我的show.html.haml

:javascript 
    var map; 
    var riders = #{raw @riders.to_json} 

    function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
    center: { lat: 3, lng: 102 }, 
    zoom: 9 
    }); 
    riders.forEach(function(rider) { 
     var marker = new google.maps.Marker({ 
     position: { lat: rider.latitude, lng: rider.longitude }, //this line does not work 
     map: map, 
     animation: google.maps.Animation.DROP, 
     title: rider.name.split(' ').slice(0,2).join(' '), 
     label: rider.name.split(' ').slice(0,2).join(' '), 
    }); 
    } 

當我console.log(riders),這是結果,缺少location屬性,我需要。

authentication_token: "admin_token_16" 
branch_id: 55 
deposit_cents: 1000000 
email: "[email protected]" 
id: 19 
name: "Leilani Mosciski Corkery" 
online: false 
order_need_deposit: true 
phone:"+9860128134706" 
status: "active" 
working: false 

任何幫助或洞察深表感謝!

+0

你可以在車手的個人資料做預壓,同時從數據庫中獲取的車手 – user3775217

+0

感謝您更換播放功能@ user3775217。肯定會嘗試! –

回答

1

你是不是在表演function.So獲取車手的位置數據,用一個低於

def show 
    @riders = Rider.joins(:location).select('riders.*','locations.latitude','locations.longitude') 
end 
+0

@Iqlaas Ismail試試我的解決方案。 – krishnar

+0

我的男人,它的工作。我可否知道構建的問題是否正確?我以爲你以前也遇到過同樣的問題,你的問題是什麼? P/S:我編輯了一下你的答案。 'location'應該是單數。 Upvoted。如果你碰巧前往馬來西亞,給我一個消息!哈哈,你在我之前編輯它! –

+0

@IqlaasIsmail我明白了。其實我以爲你有很多位置。所以這是位置。我變了。 Upvote我的答案,如果你覺得它有用。謝謝你 – krishnar

相關問題