我在 Rails 中对具有父级父级的嵌套属性进行范围唯一性验证时遇到问题。
背景
我有一个带有 3 个模型的 rails 4 应用程序:
#app/models/account.rb
class Account < ActiveRecord::Base
has_many :contacts, dependent: :destroy
end
#app/models/contact.rb
class Contact < ActiveRecord::Base
belongs_to :account
has_many :email_addresses, dependent: :destroy, validate: :true, inverse_of: :contact
accepts_nested_attributes_for :email_addresses,allow_destroy: true
validates :email_addresses, presence: true
end
#app/models/email_address.rb
class EmailAddress < ActiveRecord::Base
belongs_to :contact, inverse_of: :email_addresses
validates :label, presence: true
validates :contact, presence: true
validates :email, uniqueness: true, presence: true
validates_email_format_of :email
end
问题
我想创建一个范围,以确保模型 EmailAddress 的属性 :email在帐户级别是唯一的(帐户是联系人的父级,而联系人本身就是 EmailAddress 的父级)。
正如http://guides.rubyonrails.org/active_record_validations.html所建议的,我尝试了:
class EmailAddress < ActiveRecord::Base
belongs_to :contact, inverse_of: :email_addresses
validates :label, presence: true
validates :contact, presence: true
validates :email, presence: true, uniqueness: { scope: :account,
message: "This contact email is already taken" }
validates_email_format_of :email
end
这会引发错误“列 email_addresses.account 不存在”我该怎么办?
谢谢你的帮助!