[英]Ruby on Rails - ActiveRecord validates presence if 'self.preference.present?' doesnt work
我想写一个验证偏好。 如果存在该用户的首选项记录,则它应验证:city(与belongs_to相关联)的存在。
user.rb
# attributes
# :city, :string
has_one :preference
preference.rb
# attributes
# preferred_car_brand
belongs_to :user
我尝试了此操作,但记录已保存,没有错误。
user.rb
validates :city, presence: true, if: :user_preference_exists
def user_preference_exists
self.preference.present?
end
您可以使用它来验证字段的存在。
class User < ActiveRecord::Base
validates :city, presence: true
end
它不会让活动记录以:city的空值保存用户模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.