如何将会话变量传递给 RoR 中的模型? [英] how to pass session variable to model in RoR?

查看:35
本文介绍了如何将会话变量传递给 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.

我试过了,但我发现我无法访问模型中的会话变量.我搜索了一下,知道这是模型的正常行为,RoR 不会将会话变量传递给模型.

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

有没有其他方法可以解决我的问题用例?我需要一个变量存储一个值,在所有情况下都需要MVCs,应该是独立的不同并发用户之间.

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.

这篇关于如何将会话变量传递给 RoR 中的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆