Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
When validates_presence_of is called?
5 Posts
When validates_presence_of is called?

In ROR, When validates_presence_of, validates_nemericality_of... methods are called? Are they called at object initializing period? Or they work like trigger,i,e they are called when object is created or updated or deleted?

I have no idea, i just call it and get benefits from these validation methods.

Thanks 2 all ROR engineers

Person
Forum Rating: 100
Sign In To Rate Post

Abdul,

ActiveRecord calls all of your validations for a model when you attempt to save an instance of that model. More accurately, the validations run when the #valid? method is called, and the #save and #save! methods call #valid? implicitly. You can explicitly call #valid? on your model instance if you'd like to determine if your validations are passing without actually writing the model to the database. Inversely, you can call #save with a false parameter to force ActiveRecord to skip the validations.

Keep in mind that a number of ActiveRecord methods call #save internally; for instance, #update_attributes. Confusingly, #update_attribute also saves a value to the database, but skips validations.

Hi Adam, Thanks for ur reply. I have another concern that is when has_many, has_one, has_and_belongs_to_many, belongs_to.... are called?

Person
Forum Rating: 100
Sign In To Rate Post

Abdul,

Thanks for the tip. I was wondering this myself too, but just chose to use it without understanding how it works. I should probably take the time to understand how all this works when I get a chance.

Hi Abdul,

The has_many, has_one, has_and_belongs_to_many, belongs_to are the relationships between the tables which you write in the models respectively. One instance when these are are called are when you call a relation on a object. For example consider you have a User object @user and you want to fetch all servers he owns in a data center. Then the user have has_many relation with the servers. Then you have to give

has_many :servers #(In server.rb model )

belongs_to :user # In user.rb model

and now you call @user.servers in your controller or in views then the relation has_many is called by the ActiveRecord and fetches all the related server entries of user as a array object. Similarly all the other relationships work. has_and_belongs_to_many is used when you want to give many-to-many relationships between tables.

5 Posts
Login to add your message