Rails如何设置一个不是数据库字段的临时变量

gtr*_*32x 15 activerecord ruby-on-rails

对于我的应用程序,我有不同的注册入口点,以不同的方式验证事物.

因此,在主注册中,除了电子邮件和密码字段之外,不需要任何其他内容.在另一个注册领域,还需要更多.所以在用户模型中我有

validate_presence_of :blah, :lah, :foo, :bah, :if => :flag_detected

def flag_detected
  !self.flag.nil?
end
Run Code Online (Sandbox Code Playgroud)

我想通过控制器设置该标志.但是,该标志不是数据库字段.我只是想知道这是否可以在Rails中实现,或者我在考虑这个方式有什么问题?如果是这样,实现这一目标的最佳方法是什么?谢谢.

Pet*_*ong 28

你需要的是什么 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
Run Code Online (Sandbox Code Playgroud)

基本上为您的模型attr_accessor :flag创建user.flaguser.flag = ...方法.

attr_accessible用于大规模分配保护.