gpt4 book ai didi

ruby-on-rails - Rails has_many 模型验证

转载 作者:行者123 更新时间:2023-12-03 08:58:10 25 4
gpt4 key购买 nike

大家好,目前正在使用几个相互关联的模型。这些协会工作得很好,但我试图限制可以属于护理团队模型的用户数量,我尝试了下面的验证方法,它似乎没有引发任何错误或任何东西。用户可以继续将自己添加到我试图限制数量的团队中。有任何想法吗?

用户.rb

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
validates_presence_of :phone, :city, :state, :street, :zip, presence: true, on: :create

belongs_to :care_team, optional: true
end

护理团队.rb

class CareTeam < ApplicationRecord
NUMBER_OF_PERMITTED_USERS = 3

belongs_to :user, optional: true

has_many :users

validate :validate_user_limit

private
def validate_user_limit(user)
raise Exception.new if users.count > NUMBER_OF_PERMITTED_USERS
end
end

最佳答案

documentation说,方法collection<<(object, …)

Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record. This will also run validations and callbacks of associated object(s).

这意味着当您将用户添加到护理团队时,例如

care_team.users << user

立即添加用户。您无需调用care_team.save保存更改。 CareTeam的验证将不会被应用。那是因为变化发生在 user对象:它的care_team_id属性设置为 care_team.id ,然后 user如果所有验证都通过,则保存。

因此,您可以通过更改 CareTeam 中的验证来应用限制。这样:

def validate_user_limit
if users.count > NUMBER_OF_PERMITTED_USERS
errors[:base] << "This care team has already enough users"
end
end

并调用care_team.save 显式进行验证。然而,它根本没有解决问题:此时用户已经添加到护理团队中。验证将失败,但用户仍留在护理团队中。

要解决此问题,验证应移至 User型号:

class User < ApplicationRecord
validate :validate_care_team_user_limit

private

def validate_care_team_user_limit
if care_team_id && User.where(care_team_id: care_team_id).count >= CareTeam::NUMBER_OF_PERMITTED_USERS
errors.add(:care_team_id, "User cannot be added to that care team")
end
end
end

关于ruby-on-rails - Rails has_many 模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53504371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com