To set validation inside a Model in Rails, I should write something like:
class Post < ActiveRecord::Base
validates :name, :presence => true
validates :title, :presence => true,
:length => { :minimum => 5 }
end
I can’t figure out how this works. It seems like it is calling a method named validates and is passing parameters, but this can’t be because, I believe I cannot call a method directly in a class body.
So what is actually happening in here?
update
From the answers it seems like this is calling a method from the 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
You wrote “but this can’t be because (I believe) you cannot call a method directly in a class body.”
But that’s not true — code is being executed as the class is loaded
Consider this:
You’ll get:
the puts is executed when it’s loaded. So you can use this to create other methods or do whatever you need.