如何在RoR中传递会话变量进行建模?

问题描述:

我以前在我的应用程序中使用了全局变量来传递信息.但是我遇到了一个问题,在此感谢每个人都建议我将这些数据与数据库进行会话存储.

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.

我尝试过,但是发现无法访问Model中的会话变量.我用Google搜索,知道这是Model的正常行为,RoR不会将会话变量传递给Model.

I tried, but I found that I can't access the session variable in Model. I googled and knew this is the Model normal behavior, RoR won't pass the session variable to Model.

因此,我想在验证以及控制器中使用该会话变量.

So, I would like to use that session variable in validation and also the controller....

  1. 如何传递值 会话变量转换成模型?或

  1. how to pass the value of the session variable into Models? or

我还有其他方法吗 用例?我需要一个变量存储 一个值,这是所有必需的 MVC,并且应该是独立的 在不同的并发用户之间.

is there any other method for my use case? I need a variable storing a value, which is required in all MVCs, and should be independent between different concurrent users.

谢谢大家. :)

如果我对您的理解正确,则会话变量会更改验证模型的方式.我相信正确的解决方案如下:

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

代码尚未公开,但这就是想法. if参数可以是方法的名称,您可以在其中执行任何操作.如果需要,可以有各种验证模式.例如:

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.