6

我在我的 Rails 3.2 应用程序中使用Devise,我希望能够在 Google Analytics 中添加跟踪新注册作为转换。如果可能的话,我希望将新用户定向到他们现在被重定向到的同一页面(即,可能是重定向到当前页面的直通视图,用户在创建后被重定向到)。

有人可以帮我找出使用设计的最佳方法吗?

# 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
4

2 回答 2

11

从我的头顶,我会使用闪光灯。

flash 提供了一种在动作之间传递临时对象的方法。你放在闪光灯里的任何东西都会暴露在下一个动作中,然后被清除。

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].

于 2013-08-14T01:42:53.240 回答
2

您可以从控制器执行此操作:

第 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 。

于 2016-06-25T05:31:44.023 回答