我構建了一個應用程序,該應用程序創建用戶模型並使用模型中的after_create回調方法自動創建配置文件模型和位置(稱爲生活)模型。模型配置文件屬於用戶,用戶有一個配置文件,模型位置屬於配置文件,配置文件有一個位置。Rails 3:After_create問題與acts_as_gmappable
該模型稱爲位置,使用gem地理編碼器和客戶端機器的current_ip地址來拉出用戶的當前位置,然後將地址,經度和緯度保存在同一模型中。
一切工作完美和罰款,除了當我嘗試添加到位置模型acts_as_gmappable,然後在註冊過程中,相同的模型不會自動創建,並且這阻止創建數據庫列地址和很顯然,這會導致gmapsforails的錯誤。
如何在配置文件模型中使用after_create回調,然後自動創建位置模型及其列(longitude,latitude,address,ip_address)並同時使用acts_as_gmappable之後?
我認爲這是一個與之前調用哪種方法有關的問題:after_create或gmapsforrails之一...這是因爲,如果我從位置模型中調用acts_as_gmappable,註冊用戶,並在過去回到位置模型acts_as_gmappable,一切工作正常,並顯示谷歌地圖。
感謝大家可能會以某種方式強調我的腦海裏......
(1)剖面模型
class Profile < ActiveRecord::Base
# Setup model relationships (has_many require plural)
belongs_to :user
has_one :living
after_create :create_living
accepts_nested_attributes_for :living
# Setup accessible (or protected) attributes for your model
attr_accessible :registration_ip, :registration_timezone, :registration_address, :registration_address_components, :latitude, :longitude, :living_attributes
# Setup Geocoder routine
geocoded_by :registration_ip
after_validation :geocode
reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
obj.registration_address_components = ActiveSupport::JSON.encode(geo.address_components)
obj.registration_address = geo.address
end
end
after_validation :reverse_geocode
end
(2)居住模式
class Living < ActiveRecord::Base
# Setup model relationships
belongs_to :profile
# Setup accessible (or protected) attributes for your model
attr_accessible :current_ip, :current_timezone, :current_address, :current_address_components, :latitude, :longitude, :gmaps
geocoded_by :current_ip
after_validation :geocode, :if => :current_ip_changed?
reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
obj.current_address_components = ActiveSupport::JSON.encode(geo.address_components)
obj.current_address = geo.address
end
end
after_validation :reverse_geocode, :if => :current_ip_changed?
acts_as_gmappable :lat => 'glat', :lng => 'glng', :check_process => :prevent_geocoding,
:address => "current_address", :normalized_address => "current_address",
:msg => "Sorry, not even Google could figure out where that is"
def prevent_geocoding
current_address.blank? || (!latitude.blank? && !longitude.blank?)
end
end
注意的create_before該配置文件位於用戶模型中。 使用此係統,每次用戶註冊時,應用程序都會自動在用戶表中創建用戶記錄,在配置文件表中創建配置文件記錄,並在活動記錄中創建活動記錄。 除非在生活模型中添加acts_as_gmappable,否則一切都可以完美平滑。此時,生活模式表中的記錄不會自動創建,顯然谷歌地圖不起作用,因爲無法在生存模型表中找到地址(生存模型將爲零)。
我在想,也許是由於在模型中使用的before_create方法,要添加一張地圖到生活中,我需要創建另一個模型讓我說gmapliving屬於生活,但在那一點上,我不有想法我怎麼能訪問保存的生存模型表中的地址記錄。
請給點建議?
感謝 Dinuz
這是一個有點混亂,閱讀,我猜所有信息都沒有必要。我猜'gmaps4rails'試圖無法成功地進行地理編碼。你有沒有嘗試做:'def prevent_geocoding; new_record? || current_address.blank? || (!latitude.blank? &&!longitude.blank?); 結束' – apneadiving 2012-03-08 22:18:42
爲什麼你需要gmaps4rails地理編碼,因爲你使用geocoder? – apneadiving 2012-03-08 22:20:32
我想要地圖......就這些!我想在同一張地圖上顯示註冊位置和當前位置。我不想使用gmaps4rails進行地理編碼,而是想使用它可以顯示的地圖。 – Dinuz 2012-03-11 20:21:41