Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

activerecord - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...