Rails 如何设置不是数据库字段的临时变量 [英] Rails how to set a temporary variable that's not a database field
问题描述
对于我的应用,我有不同的注册入口点来验证不同的东西.
For my app, I have different signup entry points that validate things differently.
因此,在主注册中,除了电子邮件和密码字段外,什么都不需要.在替代注册字段中,需要更多.所以在用户模型中我有
So in the main signup, nothing is required except for the email and password field. In an alternative signup field, many more are required. So in the user model I have
validate_presence_of :blah, :lah, :foo, :bah, :if => :flag_detected
def flag_detected
!self.flag.nil?
end
我想通过控制器设置那个标志.但是,该标志不是数据库字段.我只是想知道这是否可以在 Rails 中实现,或者我的想法有问题?如果是这样,实现这一目标的最佳方法是什么?谢谢.
I want to set that flag through the controller. However that flag isn't a database field. I'm just wondering if this is achievable in Rails or there is something wrong with the way that I am thinking about this? If so, what's the best way to achieve this? Thanks.
推荐答案
你需要的是 attr_accessor
class User < ActiveRecord::Base
attr_accessor :flag
attr_accessible :flag # if you have used attr_accessible or attr_protected else where and you are going to set this field during mass-assignment. If you are going to do user.flag = true in your controller's action, then no need this line
end
基本上 attr_accessor :flag
为您的模型创建 user.flag
和 user.flag = ...
方法.
basically attr_accessor :flag
create the user.flag
and user.flag = ...
methods for your model.
和 attr_accessible
用于批量赋值保护.
and attr_accessible
is for mass-assignment protection.
这篇关于Rails 如何设置不是数据库字段的临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!