Rails如何设置不是数据库字段的临时变量
对于我的应用程序,我有不同的注册入口点,以不同的方式validation事物。
因此,在主注册中,除了电子邮件和密码字段外,不需要任何其他内容。 在另一个注册领域,还需要更多。 所以在用户模型中我有
validate_presence_of :blah, :lah, :foo, :bah, :if => :flag_detected def flag_detected !self.flag.nil? end
我想通过控制器设置该标志。 但是,该标志不是数据库字段。 我只是想知道这是否可以在Rails中实现,或者我在想这个问题的方式有什么问题? 如果是这样,实现这一目标的最佳方法是什么? 谢谢。
你需要的是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 = ...
方法。
和attr_accessible
用于质量分配保护。
跟进最佳实践辩论:
创建一个满足您需求的方法。 即save_with_additional_validation。 这是更加清晰和自我记录的代码,并以相同的方式工作。 只需调用此方法而不是save()
看来你需要定义setter方法
class User < ActiveRecord::Base attr_accessible :flag def flag=(boolean) boolean end end