Reputation: 323
Just a quick question on the validates() method. When you're using it in the model, is there a way to write them to use the least amount of lines as possible?
Example say this is my model
class Items < ActiveRecord::Base
validates :title, :price, presence: true
end
And say I want to add numericality to price and uniquness to title.
is there a way to write that on one line instead of doing
validate :title, uniqueness: true
validate :price, numericality: {greater_or_equal_to: 0.01}
Hopefully the question makes sense.
Upvotes: 1
Views: 99
Reputation: 357
You can organize multiple attributes on one line that share the same validations
validates :foo, :bar, presence: true
validates :x, :y, numericality: { allow_blank: true }
This works really well for me. It's not unusual in my work to deal with tables with 20+ columns, reviewing all of those on one line of code would be a nightmare. You could write a custom validation method to try and put things on one line, but I don't think that's worth the effort. IE
validate :custom_method
Followed by:
def custom_method
errors.add(:foo, 'must have value') if self.foo.nil? ; errors.add(:bar, 'must have value') if self.bar.nil?
end
I hope that illustrates why accepting the extra line may be ok in the long run.
edit
Rails doesn't seem to complain if you were to do something like:
validates :foo, length: { maximum: 12 }, presence: true ; validates :bar, length: { maximum: 40 }
Upvotes: 1