how to pass session variable to model in RoR?

前端 未结 4 1192
时光取名叫无心
时光取名叫无心 2021-01-13 07:06

I used a global variable in my app for passing information before. But I got a problem and thanks everyone here suggested me to store those data in session with database.

4条回答
  •  渐次进展
    2021-01-13 07:32

    If I understand you correctly, a session variable changes the way you validate the model. I believe the correct solution for this is the following:

    class Blog < ActiveRecord::Base
      attr_accessor :validate_title
    
      validate_presence_of :title, :if => :validate_title
    end
    
    class BlogsController < ApplicationController
      def new
        @blog = Blog.new
        @blog.validate_title = session[:validate_title]
      end
    end
    

    The code has not been testet, but that's the idea. The if argument can be the name of a method and you can do whatever you want in there. You can have various validation modes if you want. For example:

    class Blog < ActiveRecord::Base
      attr_accessor :validation_mode
    
      validate_presence_of :title, :if => :validate_title
    
      def validate_title
        validation_mode == "full" or validation_mode == "only_title"
      end
    end
    
    class BlogsController < ApplicationController
      def new
        @blog = Blog.new
        @blog.validate_mode = session[:validate_mode]
      end
    end
    

    For more information, read the guide on validation.

提交回复
热议问题