Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 982
gtr32x Avatar asked Mar 14 '12 06:03

gtr32x


3 Answers

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.

like image 62
PeterWong Avatar answered Nov 04 '22 08:11

PeterWong


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()

like image 3
mmlac Avatar answered Nov 04 '22 08:11

mmlac


It seems like you need to define setter method

 class User < ActiveRecord::Base
   attr_accessible :flag

   def flag=(boolean)
     boolean
   end
 end
like image 1
evfwcqcg Avatar answered Nov 04 '22 06:11

evfwcqcg