루프에 통합하려는 컨트롤러 중 일부에 반복되는 코드가 있지만이 방법이 고유 한 것처럼 보이기 때문에 명확한 지침을 찾을 수 없습니다 gmaps4rails의 사용 사례. 인스턴스 변수 배열을 만들려고했지만 작동하지 않는 것 같습니다! 내가 원하는 코드 통합하기 :컨트롤러 내부의 인스턴스 변수 루프
stores_controller.rb ->
class StoresController < ApplicationController
def map
@rep1 = Store.where(:user_id => "1")
@rep2 = Store.where(:user_id => "10")
@rep3 = Store.where(:user_id => "11")
@rep4 = Store.where(:user_id => "12")
@rep5 = Store.where(:user_id => "13")
@rep6 = Store.where(:user_id => "14")
@rep7 = Store.where(:user_id => "15")
@rep8 = Store.where(:user_id => "16")
@rep9 = Store.where(:user_id => "17")
@repA = Store.where(:user_id => "18")
@hash1 = Gmaps4rails.build_markers(@rep1) do |store, marker|
marker.lat store.lat
marker.lng store.long
marker.title store.name
marker.infowindow "#{store.store_infowindow}"
marker.picture({
:url => "//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=TP|81DF08|000000",
:width => 52,
:height => 32
})
end
@hash2 = Gmaps4rails.build_markers(@rep2) do |store, marker|
marker.lat store.lat
marker.lng store.long
marker.title store.name
marker.infowindow "#{store.store_infowindow}"
marker.picture({
:url => "//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=BS|267AD2|D9E1FF",
:width => 52,
:height => 32
})
end
@hash3 = etc, etc, etc...
가 나는 또한 좋은 측정을위한 뷰 파일에서 내지도 JS에서 마커 로더를 포함하는 것,
map.html.erb ->
markers = handler.addMarkers(<%=raw @hash1.to_json %>), handler.addMarkers(<%=raw @hash2.to_json %>),
handler.addMarkers(<%=raw @hash3.to_json %>), handler.addMarkers(<%=raw @hash3.to_json %>),
handler.addMarkers(<%=raw @hash4.to_json %>), handler.addMarkers(<%=raw @hash5.to_json %>),
handler.addMarkers(<%=raw @hash6.to_json %>), handler.addMarkers(<%=raw @hash7.to_json %>),
handler.addMarkers(<%=raw @hash8.to_json %>), handler.addMarkers(<%=raw @hash9.to_json %>),
handler.addMarkers(<%=raw @hashA.to_json %>);
gmaps4rails 마커 건물 @hash 변수는 여기에 표시된이 처음이 넘어 모두 10 명 담당자를 통해 개별 루프를 계속합니다. 이 해시 내의 유일한 두 변수는 'build_markers (@ rep #)'호출과 'chld = TP | 81DF08 | 000000'호출로, 각 사용자에 대한 마커의 이니셜과 색상을 나타냅니다. 나는 초심자입니다. 그래서 처음부터 완전히 잘못을 저지르고있을 수도 있습니다. 모든 조언을 부탁드립니다. 감사!
편집 ->
그 변경 필요한 유일한 하드 코딩 된 변수가 된 이후에, 내 사용자 테이블에 "마커"열을 추가하는 것만 큼 간단 었죠 내 통합 코드, 지도 표시의 URL에서 '# {store.user.marker}'의 형태 :
stores_controller.rb ->
def map
@stores = Store.all
@hash = Gmaps4rails.build_markers(@stores) do |store, marker|
marker.lat store.lat
marker.lng store.long
marker.title store.name
marker.infowindow "#{store.store_infowindow}"
marker.picture({
:url => "//chart.apis.google.com/chart?chst=d_map_pin_letter&chld=#{store.user.marker}",
:width => 52, :height => 32
})
end
respond_to do |format|
format.html
format.json { render json: @hash }
end
end
코드에 ID를 하드 코딩하는 것은 정말 나쁜 코드 냄새입니다. ID가 데이터베이스에 의해 순차적으로 작성되므로 코드를 테스트 할 수 없습니다. 대신 리소스를 사용할 수 있어야하고 필터링 할 수있는 합리적인 방법을 생각해야합니다. – max
불행히도이 방법은 마커의 색상을 제한합니다. 각 사용자의지도에 동적 마커 색상이 있어야하기 때문입니다. –
당신은'store.user'에 의해 사용자를 얻을 수 있어야합니다 - 색상을 users 테이블에 저장할 수 있습니다. 당신이하는 일은 실제로 애플 리케이션을 개발하는 실제 방법이 아닙니다 ... – max