Reputation: 47
My Rails5.1.4 project ha had Station model and there are some saved records.
class Station < ApplicationRecord
end
> Station.first
# => #<Station:0x0055f5ca447d78 id: 1, name: nil>
Then I added new validation(presence checking for name).
class Station < ApplicationRecord
with_options on: [:publishing] do
# added new validation
validates :name, presence: true
end
end
Here, if validate! method called without attributes changing. validate! method returned true.
> reload!
> station = Station.first
# => #<Station:0x0055f5cf4b6228 id: 1, name: nil>
> station.validate!(context: :publishing) # without attributes changing
# => true
# expected ActiveRecord::RecordInvalid raising.
Here is an one problem for me.
I expected ActiveRecord raised ActiveRecord::RecordInvalid
because I added presence validation for name.
can I do like this?
Regards
Upvotes: 1
Views: 964
Reputation: 601
Try using valid?
station = Station.first
station.valid?
It should work fine :)
Note: other answers recommend using validate both should work fine as validate is an alias for valid?. Check this
Upvotes: 4
Reputation: 754
Wrong argument. Try to call it like this:
station.validate!(:publishing)
Docs: https://apidock.com/rails/v4.2.7/ActiveRecord/Validations/validate%21
Upvotes: 6