I have that in my migration for table
t.string :name, :null => false
When user trying to save model with null name then it gives an error. How can I handle it and give back beautiful message? I don't wanna use validates
validates :name, presence: true
You can try Migrations Validators project ( https://github.com/vprokopchuk256/mv-core ). It allows you to define validations on a database level.
Example:
def change
create_table :items do |t|
t.string :name, presence: true
end
end
And you can define event beautiful message:
def change
create_table :items do |t|
t.string :name, presence: {message: 'not beautiful', as: :trigger}
end
end
In this case validation would be defined as condition inside trigger. You can define that trigger name or trigger event. Just see documentation to the project. In case validation is failed then db exception with specified message is risen.
And if you want to handle error from that constraint graciously you can do it in this way:
class Item < ActiveRecord::Base
enforce_migration_validations
end
As result:
Item.new(name: nil).valid?
=> false
Item.new(name: 'Mr. Smith').valid?
=> true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.