[英]How do I prevent a user from being saved on a validation on an associated model in ruby on rails?
I have the following setup with the backend to a mobile app:我在移动应用程序的后端进行了以下设置:
class User < ApplicationRecord
has_many :mobile_device_infos
...
end
class MobileDeviceInfo < ApplicationRecord
belongs_to :user
...
end
Every time the user logs in, a user device id is saved to mobile device info table, along with the last login time.每次用户登录时,都会将用户设备 ID 和上次登录时间一起保存到移动设备信息表中。 A new device id will create a new record for the same user account.新的设备 ID 将为同一用户帐户创建新记录。 When a new user is created, then a search needs to be done via a validation that prevents the user from being saved if there are more than 2 duplicate accounts with the same device id where the last login time is less than one hour old.创建新用户时,如果有超过 2 个具有相同设备 ID 的重复帐户且上次登录时间小于一小时,则需要通过验证来完成搜索,以防止保存用户。 How can I create a validation that checks the mobile device info table each time a user is created that will prevent the user from being saved if there are more than 2 of the same device id?如何创建一个验证,每次创建用户时检查移动设备信息表,如果有超过 2 个相同的设备 ID,将阻止用户被保存?
I would imagine that I would need a validation on the MobileDeviceInfo
table and accepts_nested_attibutes_for
on the user model.我想我需要对MobileDeviceInfo
表进行验证,并在用户accepts_nested_attibutes_for
上接受_nested_attibutes_for。 How would I go about creating this type of validation?我将如何 go 创建这种类型的验证?
possible when user login you should check if device already exist to prevent duplicates - MobileDeviceInfo.find_or_initialize_by(base_params)
.可能在用户登录时您应该检查设备是否已经存在以防止重复 - MobileDeviceInfo.find_or_initialize_by(base_params)
。 Or you can add custom validator validates_with MobileDeviceInfoCustomValidator
to user model.或者您可以将自定义验证器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
also all validation in MobileDeviceInfo
model should work throw nested attributes. MobileDeviceInfo
model 中的所有验证也应该工作抛出嵌套属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.