我在我的Rails 3.2应用中使用Devise,我希望能够在Google Analytics中添加跟踪新注册作为转化。我想让新用户定向到他们被重定向到现在的同一页面,如果可能的话(也就是说,可以通过重定向到当前页面的视图,用户在创建后被重定向到)。
有人可以帮我找出使用Devise做到这一点的最佳方法吗?
# users/registrations_controller.rb
# POST /resource
def create
build_resource
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource)
end
答案 0 :(得分:10)
从我的头顶,我会使用闪光灯。
在registrations_controller.rb
:
if resource.active_for_authentication?
flash[:user_signup] = true # or something that you find more appropriate
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
然后,在注册后重定向到的视图中,我会根据flash[:user_signup]
的存在情况呈现必要的代码以触发Google Analytics事件。
答案 1 :(得分:1)
您可以从控制器执行此操作:
第1步:为了使其有条理,您可以使用以下内容创建文件app/controllers/concerns/trackable.rb
:
module Trackable
extend ActiveSupport::Concern
def track_event(category, action)
push_to_google_analytics('event', ec: category, ea: action)
end
def track_page_view
path = Rack::Utils.escape("/#{controller_path}/#{action_name}")
push_to_google_analytics('pageview', dp: path)
end
private
def push_to_google_analytics(event_type, options)
Net::HTTP.get_response URI 'http://www.google-analytics.com/collect?' + {
v: 1, # Google Analytics Version
tid: AppSettings.google_analytics.tracking_id,
cid: '555', # Client ID (555 = Anonymous)
t: event_type
}.merge(options).to_query if Rails.env.production?
end
end
第2步:替换跟踪ID 。
第3步:最后,在控制器中跟踪您的转化次数:
# app/controllers/confirmations_controller.rb
class ConfirmationsController < Devise::ConfirmationsController
include Trackable
after_action :track_conversion, only: :show
private
def track_conversion
track_event('Conversions', 'from_landing_page')
# or # track_event('Conversions', user.email)
end
end
额外:您还可以使用track_page_view
方法跟踪不具有观看次数的特定操作(例如API请求)。
此处有更多信息:https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide。