How does validation work in ActiveRecord?

To set up validation inside the model in Rails, I have to write something like:

class Post < ActiveRecord::Base validates :name, :presence => true validates :title, :presence => true, :length => { :minimum => 5 } end 

I can’t understand how this works. It looks like he is calling a method called validates and passing parameters, but this cannot be, because, I believe, I can not call the method directly in the body of the class.

So what is really going on here?

Update

From the answers, it seems that this is a method call from an inhereted Base class, but then why does this not work ?:

 class Parent def foo puts "called foo" end end class Child < Parent foo foo end 
+4
source share
4 answers

You wrote "but this cannot be, because (I believe) you cannot call a method directly in the body of the class."

But this is not true --- the code is executed when the class is loaded

Consider this:

 class Hi puts "yo" end 

You'll get:

 yo => nil 

puts is executed at boot time. That way you can use this to create other methods or do whatever you need.

+1
source

Why, in your opinion, you cannot call a method in a class? These are class methods, and so they are called - see, for example, the bit on validation here and the definition of validates in the api class method here

You can see how it works here:

  class Foo def self.bar p 'hello' end end Foo.bar #=> hello class Thing < Foo bar end #=> hello 
0
source

Yes, basically what happens. These validation methods are hooks that Rails knows to load and call before saving and updating. The Rails Guide contains a bit more information, but basically that.

0
source

validates is a method inherited from ActiveRecord :: Base. You can follow the path from ActiveRecord :: Base to validates.rb and see what happens !;)

0
source

Source: https://habr.com/ru/post/1391703/


All Articles