我有两个模型Person
和Address
:
class Person < ApplicationRecord
has_one :address
end
class Address < ApplicationRecord
belongs_to :person
end
如何验证每个指向另一个?
我想做一些类似的事情:
class Person < ApplicationRecord
has_one :address
validates :address, presence: true
end
当然,这是行不通的,因为address
不是Person
的属性。
在 Rails 中,确保一条记录与另一条记录具有有效关联的正确方法是什么?
class Person < ApplicationRecord
has_one :address, required: true
end
class Address < ApplicationRecord
belongs_to :person
end
请参阅 https://apidock.com/rails/v5.2.3/ActiveRecord/Associations/ClassMethods/has_one 选项部分中的required
选项
现在自动需要 Rails 5 中的belongs_to
,因此您无需在 Address.
中放置任何不同的东西
您需要使用 validates_associated :address
来验证关联