I want all my models to inherit a validation present in my ApplicationRecord file except the user
model. Is there a way to achieve that?
This is the line validates :user_id, presence: true
I wouldn't recommend putting that in ApplicationRecord
since it's meant to be the parent of all modules, but if you really want to do it:
class ApplicationRecord < ActiveRecord::Base
validates :user_id, presence: true, unless: 'self.class.to_s == "User"'
...
end
But i strongly suggest against it. This would make your code counter intuitive and future developers would have trouble understanding why it functions like that. Not to mention any future records you create, you explicitly have to set presence: false
.
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.