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

标签 ruby-on-rails validation model

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

用户.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/

相关文章:

php - Symfony 2 Form - 表单无效时刷新保护

python - QSortFilterProxyModel 不应用 SortRole

python - 当 child 不能继承时如何创建基类?

spring - 如何遍历 JSP 页面上的所有模型属性?

css - 在 Rails 中出于布局和 CSS 目的对网页进行分类

javascript - 从 Rails 中的不同 CoffeeScript 文件调用函数

ruby-on-rails - Rails 3表单助手: UTF8 and other hidden fields

ruby-on-rails - AWS SES 和 Rails。我的应用程序不发送邮件

Angular 形式验证 : compare two fields in different form groups

php - 在没有 http ://in symfony 的情况下验证 url