Reputation: 339
I want to allow posting either messages without images or with a unique image, I added following code in my model
validates :image_fingerprint, :uniqueness => true
It forbids posting similar images but it forbids as well posting more than one message without image. I tried to add
:allow_blank => true
and
:allow_nil => true
but it leads to the following error:
TypeError in PostsController#create can't convert nil into String
How can I fix it?
Upvotes: 1
Views: 244
Reputation: 24815
You can use :unless
on validation, only if this attribute not blank
validates :image_fingerprint, :uniqueness => true,
:unless => Proc.new { |a| a.image_fingerprint.blank? }
Reference:
You can associate the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
Finally, it’s possible to associate :if and :unless with a Proc object which will be called. Using a Proc object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.
http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation
Upvotes: 2