假设我有一个 ActiveRecord 关联,例如:
class City < ActiveRecord::Base
belongs_to :state
end
没有国家的城市应该是无效的。似乎这两个都是可能的验证:
validates :state, presence: true
# OR
validates :state_id, presence: true
我猜它们是相同的,因为:
belongs_to
创建方法state
和state=
state=
设置state_id
但是,我刚刚通过更改它以检查 id 而不是对象来修复失败的规范。
这两种验证方式都可以接受吗?如果是这样,您什么时候使用其中一种?