我正在尝试逐渐参与我的实用程序应用程序,人们可以使用它而无需注册,例如notepad.cc和jsfiddle.net,我计划在用户“写入”应用程序时为其创建一个访客用户(使用Devise)。
我在Devise wiki https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user上找到了这个指南,其中显示了如何在浏览器会话期间创建访客用户。我想要的是让用户在后续访问中继续使用相同的来宾帐户,直到他注册,或者当我引入更多功能的订阅计划时。
如何修改指南中的内容以使其成为可能?
上面链接指南中的代码:
# 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
在控制器中使用它:
@thing.user = current_or_guest_user
@thing.save
答案 0 :(得分:15)
经过一些牦牛皮剃须后,我设法让它上班。这是工作代码:
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
如果你能告诉我更好的方法,我会接受另一个答案。
答案 1 :(得分:4)
上述解决方案效果很好。
不要忘记设置helper_method :current_or_guest_user
以使视图中的方法可访问。花了一些时间才弄清楚。