![](/img/trans.png)
[英]Nested resource being destroyed but associated model should prevent this (validation in Rails 5)
[英]How do I prevent a user from being saved on a validation on an associated model in ruby on rails?
我在移動應用程序的后端進行了以下設置:
class User < ApplicationRecord
has_many :mobile_device_infos
...
end
class MobileDeviceInfo < ApplicationRecord
belongs_to :user
...
end
每次用戶登錄時,都會將用戶設備 ID 和上次登錄時間一起保存到移動設備信息表中。 新的設備 ID 將為同一用戶帳戶創建新記錄。 創建新用戶時,如果有超過 2 個具有相同設備 ID 的重復帳戶且上次登錄時間小於一小時,則需要通過驗證來完成搜索,以防止保存用戶。 如何創建一個驗證,每次創建用戶時檢查移動設備信息表,如果有超過 2 個相同的設備 ID,將阻止用戶被保存?
我想我需要對MobileDeviceInfo
表進行驗證,並在用戶accepts_nested_attibutes_for
上接受_nested_attibutes_for。 我將如何 go 創建這種類型的驗證?
可能在用戶登錄時您應該檢查設備是否已經存在以防止重復 - MobileDeviceInfo.find_or_initialize_by(base_params)
。 或者您可以將自定義驗證器validates_with MobileDeviceInfoCustomValidator
添加到用戶 model。
app/validators/mobile_device_info_custom_validator.rb
# frozen_string_literal: true
class MobileDeviceInfoCustomValidator < ActiveModel::Validator
def validate(record)
# your custom logic to validate
return if # valid_case_logic
error = I18n.t('validators.errors.messages') #your error if needed
record.errors.add(:mobile_device_info, error)
end
end
MobileDeviceInfo
model 中的所有驗證也應該工作拋出嵌套屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.