TimeString
TimeString

Reputation: 1798

What exactly are validates and has_many?

I'm not asking what are the purposes or what they are doing, these are already explained in other tutorials (e.g., this). I feel like these words are some sort of defined methods, potentially from a super class (i.e., ActiveRecord::Base), But it makes no sense to call a method/function beyond any method. Or is it a language feature and I should just take these two words as built-in keywords? Are they still in the scope of Ruby or the syntax is from Ruby on Rails framework?

To give you a concrete example:

class Person < ActiveRecord::Base
    validates :email, confirmation: true
    validates :email_confirmation, presence: true
end

Upvotes: 0

Views: 35

Answers (3)

Jordan Running
Jordan Running

Reputation: 106077

As I mentioned in my comment above, validates and has_many are normal class methods in Ruby.

With regard to your question "Can you make a [method] call beyond a method?" I feel like the code you cited supplies the answer: Yes.

Unlike some programming languages, in Ruby class and module definitions aren't special unicorns. You can execute any Ruby code inside them. Here's an example:

class Foo
  def self.say_goodbye
    puts "Goodbye!"
  end

  puts "Hello!"
  say_goodbye
end

Try it yourself to see what it does.

Okay, spoilers: This code creates the class Foo and immediately prints Hello! and Goodbye!. On the second-to-last line say_goodbye is a method call equivalent to self.say_goodbye. Since you're inside its class definition, self is Foo, the class itself, so it's equivalent to Foo.say_goodbye.

In the case of validates and has_many, Rails defines these in modules (ActiveModel::Validations and ActiveRecord::Associations, respectively) that are ultimately included in ActiveRecord::Base. I say "ultimately" because Rails does it somewhat circuitously via its autoloading mechanism, but at its core it's all just plain old Ruby.

Upvotes: 2

BoP
BoP

Reputation: 457

Both of them has_many and validates are methods defined inside of rails gems. They describing properties of rails models (Rails is based on MVC) - how model should be validated before saving and how it relates to other models.

Here are definitions: validates, has_many, and many more...

Upvotes: 2

Drew
Drew

Reputation: 2663

the names of methods

also, guessing validates would add additional methods to associated class

also, guessing both validates as well as has_many could be considered to employ metaprogramming techniques

Upvotes: 0

Related Questions