1

I followed Railscast #393 to implement guest users into my application. The only problem I'm having with this approach is that it requires the user to still click a button to create the user (albeit without signing up). My goal is to have this occur automatically, but without happening every time the page is reloaded or visited again. I'm at a loss on how to go about this.

user_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = params[:user] ? User.new(params[:user]) : User.new_guest
    if @user.save
      current_user.move_to(@user) if current_user && current_user.guest?
      session[:user_id] = @user.id
      redirect_to root_url
    else
      render "new"
    end
  end
end

user.rb

class User < ActiveRecord::Base
    attr_accessible :name, :provider, :uid, :email

    has_many :posts, :dependent => :destroy
    has_many :comments, :dependent => :destroy

    def self.new_guest
        new { |u| u.guest = true }
    end
    def move_to(user)
      posts.update_all(user_id: user.id)
      comments.update_all(user_id: user.id)
    end
end

application.html.erb

<ul>
    <li><%= button_to "Try it for free!", users_path, method: :post %></li>
</ul>

I can provide any additional information necessary to help answer this question.

1 Answer 1

4

You could potentially handle this in a before_filter, but you'd want to consider that you'd be creating a new guest user any time that anyone or anything (Google bot, for instance) requests a page from your site without an existing session. Requiring some sort of user action to kick it off is probably a good thing. That being said, if you really wanted to do it you could do something like this in your ApplicationController:

before_filter :create_guest_if_needed
def create_guest_if_needed
  return if session[:user_id] # already logged in, don't need to create another one
  @user = User.new_guest
  @user.save
  session[:user_id] = @user.id
  # do anything else you need here...
end
1
  • This did the job. I put it in as a before filter for the new and create methods for my posts_controller.rb. Works like a charm, thanks so much!
    – anater
    Commented Sep 27, 2013 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.