title: Automatically Create Guest User With Rails
body: <p>I followed <a href="http://railscasts.com/episodes/393-guest-user-record" rel="nofollow">Railscast #393</a> 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.</p>
  
  <p>user_controller.rb</p>
  
  <pre><code>class UsersController &lt; 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 &amp;&amp; current_user.guest?
        session[:user_id] = @user.id
        redirect_to root_url
      else
        render "new"
      end
    end
  end
  </code></pre>
  
  <p>user.rb</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
      attr_accessible :name, :provider, :uid, :email
  
      has_many :posts, :dependent =&gt; :destroy
      has_many :comments, :dependent =&gt; :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
  </code></pre>
  
  <p>application.html.erb</p>
  
  <pre><code>&lt;ul&gt;
      &lt;li&gt;&lt;%= button_to "Try it for free!", users_path, method: :post %&gt;&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>I can provide any additional information necessary to help answer this question.</p>