small medium large xlarge

06 Apr 2013, 15:24
Louis Rhys (22 posts)

I am a C# developer, new to ruby. I still can’t understand many of the method call examples in the book up to this point. For example, the @validates@ call

  validates :title, :description, :image_url, presence: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}

What are exactly passed in these calls? Initially I thought the first one it seems that it is passing several symbols and a hash table at the end. But in the second one, there is only one symbol, and numericality has weirder syntax than presence.

What parameters can I pass when calling validates? How can the symbols get translated to what I want (e.g. validating whether the object has certain attributes)

What hashed parameters (like presence, numericality, etc.) can I pass and how will ruby translate the parameter to the corresponding check?

06 Apr 2013, 18:49
Sam Ruby (633 posts)

For the syntax question, validates takes a list of symbols followed by a single hash. In the first case, the hash is equivalent to this:

{ presence: true }

In the second case, it is a hash where the key is a symbol, and the value is a hash:

{ numericality: {greater_than_or_equal_to: 0.01} }

As to the second question, the complete list of validations can be found in the online documentation.

07 Apr 2013, 04:57
Louis Rhys (22 posts)

I see. Inside the validator, how does the symbol gets translated to the actual value?

07 Apr 2013, 11:08
Sam Ruby (633 posts)

C# provides a facility called Reflection that allows you to interact with the type system. Ruby is more dynamic than C#, and this functionally is pervasive.

The book introduces Rails console in section 14.4, but you can use it now. Enter @rails console@, and then:


More information on the send method can be found in the Ruby documentation.

You must be logged in to comment