gpt4 book ai didi

ruby-on-rails - 逐步参与,持续的 guest 用户与 Devise

转载 作者:数据小太阳 更新时间:2023-10-29 06:52:05 25 4
gpt4 key购买 nike

我正在尝试在我的实用程序中设置渐进式参与,人们无需注册即可使用,例如notepad.cc 和 jsfiddle.net 以及我计划在用户“写入”应用程序时为用户创建一个 guest 用户(使用 Devise)。

我在 Devise wiki 上找到了这个指南 https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user它显示了如何在浏览器 session 期间创建访客用户。我想要的是用户在后续访问中继续使用相同的访客帐户,直到他注册为止,也许当我推出更多功能的订阅计划时。

如何修改指南中的内容以实现此目的?

上面链接的指南中的代码:

# file: app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

protect_from_forgery

# if user is logged in, return current_user, else return guest_user
def current_or_guest_user
if current_user
if session[:guest_user_id]
logging_in
guest_user.destroy
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end

# find guest_user object associated with the current session,
# creating one as needed
def guest_user
User.find(session[:guest_user_id].nil? ? session[:guest_user_id] = create_guest_user.id : session[:guest_user_id])
end

# called (once) when the user logs in, insert any code your application needs
# to hand off from guest_user to current_user.
def logging_in
end

private
def create_guest_user
u = User.create(:name => "guest", :email => "guest_#{Time.now.to_i}#{rand(99)}@email_address.com")
u.save(false)
u
end

end

并在 Controller 中使用它:

@thing.user = current_or_guest_user
@thing.save

最佳答案

在剃了一些牦牛毛之后,我设法让它开始工作。这是工作代码:

class ApplicationController < ActionController::Base

protect_from_forgery

# if user is logged in, return current_user, else return guest_user
def current_or_guest_user
if current_user
if cookies[:uuid]
logging_in # Look at this method to see how handing over works
guest_user.destroy # Stuff have been handed over. Guest isn't needed anymore.
cookies.delete :uuid # The cookie is also irrelevant now
end
current_user
else
guest_user
end
end

# find guest_user object associated with the current session,
# creating one as needed
def guest_user
User.find_by_lazy_id(cookies[:uuid].nil? ? create_guest_user.lazy_id : cookies[:uuid])
end

# called (once) when the user logs in, insert any code your application needs
# to hand off from guest_user to current_user.
def logging_in
# What should be done here is take all that belongs to user with lazy_id matching current_user's uuid cookie... then associate them with current_user
end

private

def create_guest_user
uuid = rand(36**64).to_s(36)
temp_email = "guest_#{uuid}@email_address.com"
u = User.create(:email => temp_email, :lazy_id => uuid)
u.save(:validate => false)
cookies[:uuid] = { :value => uuid, :path => '/', :expires => 5.years.from_now }
u
end

end

如果您能告诉我更好的方法,我会接受另一个答案。

关于ruby-on-rails - 逐步参与,持续的 guest 用户与 Devise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8267230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com