Post Redirect Get pattern in Rails

前端 未结 6 1302
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 15:19

How can I implement PRG in Rails?

I used PRG in Rails, but I am not totally convinced it\'s right. I was wondering is there any better way to handle it in Rails?

6条回答
  •  抹茶落季
    2021-01-05 15:56

    Use the session, Luke

    The way you implemented it in your blog post is quite fine, however you may want to use session instead of flash to store your @user and optionally use the ActiveRecord session store to keep cookies from getting bloated.

    From ActionController::Base documentation

    ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and, unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set

    config.action_controller.session_store = :active_record_store
    

    in your config/environment.rb and run rake db:sessions:create.

    So you should…

    class UsersController < ApplicationController
    
      def new
        @user = session[:user] || User.new
      end
    
      def create
        @user = User.new(params[:user])
    
        if @user.save
          # clears previously stored user if there is any
          session[:user] = nil
          redirect_to '/'
        else
          session[:user] = @user
          redirect_to :action => :new
        end
      end
    end
    

提交回复
热议问题