A
A
andrew4habr2015-06-16 09:41:20
Ruby on Rails
andrew4habr, 2015-06-16 09:41:20

What is the preferred way to validate Ruby on Rails models?

Started learning Ruby/Rials. It was a pleasant surprise that here a lot of attention is paid to the readability of the code. Therefore, I was a little puzzled why the book uses the validates method instead of validates_#{param}_of, since the latter is more readable. And here actually a question, what method of validation is more preferable to use?

class Product < ActiveRecord::Base
  # Способ один. Плюсы: все аргументы начинаются на одном уровне
  validates :title, :description, :image_url, :price, presence: true
  validates :title, uniqueness: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}

  # Способ второй. Читается, как предложение
  validates_presence_of :title, :description, :image_url, :price
  validates_uniqueness_of :title
  validates_numericality_of :price, greater_than_or_equal_to: 0.01
end

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Jeiwan, 2015-06-16
@andrew4habr

The second way is outdated. Styleguides do not approve ( https://github.com/bbatsov/rails-style-guide#sexy-... ), Hound swears.
IMHO, the first way is more convenient to read, since all validations related to one field are in one line - it’s more convenient to search, because if we want to check the validation of a field, we will search for it by the name of the field.
It is preferable to use the one that is used in your project. If you are cutting something for yourself, and someone (a potential employer) will see the code, then it is better to stick to the most common style guides (again https://github.com/bbatsov/rails-style-guide) as it can show your discipline and willingness to follow best practices. If you are sawing for yourself, and no one will look at the code, then write as you like.

O
OnYourLips, 2015-06-16
@OnYourLips

The second method is IDE friendly, the first is used in the documentation.
So I would prefer the second way in other stricter languages, and the first way in Ruby.

D
Denis Krivoschekov, 2015-06-16
@densomart

Logic readability is important. A declaration, you can read without straining. Especially if everyone writes the same way, focusing on the documentation.
If you google it, there must have been a lot of discussion about this syntax change, but is it worth spending time on this ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question