Rails how to set a temporary variable that's not a database field

扶醉桌前 提交于 2019-12-30 05:48:09

问题


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

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.


回答1:


What you need is 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

basically attr_accessor :flag create the user.flag and user.flag = ... methods for your model.

and attr_accessible is for mass-assignment protection.




回答2:


Following up on the best practice debate:

Create a method that does what you want. I.e. save_with_additional_validation. This is much more clear and self-documenting code and works the same way. Just call this method instead of save()




回答3:


It seems like you need to define setter method

 class User < ActiveRecord::Base
   attr_accessible :flag

   def flag=(boolean)
     boolean
   end
 end


来源:https://stackoverflow.com/questions/9697041/rails-how-to-set-a-temporary-variable-thats-not-a-database-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!