class Sleep < ApplicationRecord
has_one :poi, as: :poitable, dependent: :destroy
accepts_nested_attributes_for :poi
在我的睡眠控制器中:
def create
@sleep = Sleep.new(sleep_params)
@sleep.user_id = current_user.id if current_user
if @sleep.save
redirect_to track_sleeps_path, notice: t(".sleep_created")
else
render :new
end
end
def sleep_params
params.require(:sleep).permit(
:name,
.......,
{ :poi_attributes => [..., :latitude, :longitude, :lonlat, :poitable_id, :poitable_type] } )
end
class Poi < ApplicationRecord
geocoded_by :full_address
after_validation :geocode, if: :will_save_change_to_address?
before_create :set_st_point
belongs_to :poitable, polymorphic: true, optional:true
当我创建一个新实例时,我通过地理编码程序获得经度和纬度。它工作得很好。
def set_st_point
if latitude.present? && longitude.present?
self.lonlat = "POINT(#{longitude} #{latitude})"
end
end
我一直在尝试“保存前”、“创建前”,但字段lonlat保持空白。
我想做的是:
def set_st_point
if latitude.present? && longitude.present?
self.lonlat = "POINT(#{longitude} #{latitude})"
self.save!
end
end