2016-08-13 102 views
0

我想写一个首选项的验证。如果此用户的首选项记录存在,它应验证城市(与belongs_to关联)的存在。Ruby on Rails - ActiveRecord验证存在如果'self.preference.present?'不工作

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 

回答

1

您可以使用它来验证字段的存在。

class User < ActiveRecord::Base 
    validates :city, presence: true 
end 

它不会让活动记录保存具有空值的用户模型:城市。

+0

我错过了说偏好应该是一个“可选关系”。有用户喜欢,没有偏好的用户。我只想验证用户是否有偏好。我更新了这个问题。 –

+0

我在模型中发现了一个错误,那个城市并不是空白的,因此验证不会产生错误,您的方法可行! –

相关问题