how to pass session variable to model in RoR?

前端 未结 4 1198
时光取名叫无心
时光取名叫无心 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:27

    Do you need the session variable as part of your model, or just as a flag to determine what to execute?

    If the former, you don't need to know where did the parameters originate, just pass the variable as an argument for some call in your method. For example:

    @user = User.new(params[:user].merge(:some_attribute => session[:some_key])

    and just add the validation as usual in the model.

    If you need that to control some flow of the execution, as you mention that should be different for different users, you may need an instance variable in your controller. Something like

    class SomeController
      before_filter :set_some_session_variable
    
      def set_some_session_variable
        @some_variable = session[:some_key]
      end
    end
    

    You could use session[:some_key] directly in your view, but is better to set it in an instance variable instead.

提交回复
热议问题