我试图在这里遵循/重现本教程https://gorails.com/episodes/referral-program-from-scratch?autoplay=1 代码在这里:https://github.com/gorails-screencasts/referral-program
到目前为止,我的代码确实为每个新注册创建了一个推荐代码。但它没有记录推荐人是谁,refered_by。那部分不起作用。
在我的应用程序控制器中我有:
before_action :set_referred_by_cookie
protected
def set_referred_by_cookie
if params[:ref]
cookies[:referred_by] = {
value: params[:ref],
expires: 30.days.from_now,
}
end
end
当我使用浏览器工具查看此内容时,我发现这部分可以正常工作: Cookie:refered_by=d6733c0da6f0; (但它没有保存到数据库)
这是我创建的用于新注册的用户的示例链接,因此看起来确实将引用转换为“referred_by” http://localhost:3000/?ref=d6733c0da6f0
这是我的用户.rb:
class User < ApplicationRecord
has_prefix_id :user
belongs_to :referred_by, class_name: "User", optional: true
has_many :referred_users, class_name: "User", foreign_key: :referred_by_id
before_validation :set_referral_code
validates :referral_code, uniqueness: true
def set_referral_code
if self.referral_code.nil?
loop do
self.referral_code = SecureRandom.hex(6)
break unless self.class.exists?(referral_code: referral_code)
end
end
end
# Call this from anywhere in your application when the user has completed their referral steps
#after_create :complete_referral!
def complete_referral!
update(referral_completed_at: Time.zone.now)
# TODO: add credit to referred_by user
end
end
这是注册控制器/设备:
class Users::RegistrationsController < Devise::RegistrationsController
invisible_captcha only: :create
protected
def build_resource(hash = {})
if cookies[:referred_by] && referrer = User.find_by(referred_by: cookies[:referred_by])
self.resource.referred_by = referrer
end
self.resource = resource_class.new_with_session(hash, session)
end
def sign_up(resource_name, resource)
sign_in(resource_name, resource)
end
end
注册控制器中的这段代码似乎不起作用?:
if cookies[:referred_by] && referrer = User.find_by(referred_by: cookies[:referred_by])
self.resource.referred_by = referrer
这就是我试图让“referred_by”工作的地方,这应该将其添加到数据库中的“referred_by_id”。忽略“referral_completed_at”,我知道这有效.. 来自数据库:
["referral_code", "ae922a5c9df8"], ["referred_by_id", nil], ["referral_completed_at", nil]]
你的
build_resource
有点倒退,你需要先设置self.resource
然后分配referred_by
,你正在错误的列上搜索:
def build_resource(hash = {})
super
if cookies[:referred_by] && referrer = User.find_by(referral_code: cookies[:referred_by])
self.resource.referred_by = referrer
end
end
sign_up
方法也是不必要。