简体   繁体   English

验证包含在创建时不起作用

[英]validate inclusion not working on create

Okay I have quite a weird scenario that I do not know how to deal with so please bear with me as I try to explain it to you. 好吧,我有一个很奇怪的场景,我不知道该如何处理,因此在我尝试向您解释时请耐心等待。

I have the following model. 我有以下模型。

class User < ActiveRecord::Base
  Roles = { pending: 'pending_user', role2: 'role2', etc: 'etc' }
  attr_accessible :role
  validates :role, inclusion: {in: Roles.values}
  before_create :add_pendng_role #Set user role to Roles[:pending]
end

Now the problem is when creating a record for the first time, this validation fails! 现在的问题是,第一次创建记录时,此验证失败! For example in my controller I have the following code: 例如,在我的控制器中,我有以下代码:

class UsersController < ActionController::Base
  @user = User.new params[:user]
  if @user.save  # ---------------   ALWAYS FAILS -------------------------------
    #do something
  else
    #do something else
  end
end

Now the reason I believe it fails is because a role is only added before_create which is called after the validations have passed. 现在,我认为它失败的原因是因为仅在验证通过后才添加一个角色before_create Now I know that I can't replace the before_create :add_role with before_validation :add_role because I think that it will add the role each time a validation is done. 现在我知道,我不能代替 before_create :add_role before_validation :add_role ,因为我认为这将每一个验证完成时添加的角色。 The reason I can't have that is because the user role will change in the application and I don't want to reset the role each time a validations are done on the user. 我之所以不能这样做,是因为用户角色将在应用程序中更改,并且我不想每次对用户进行验证时都重置角色。

Any clues on how I could tackle this? 关于如何解决这个问题的任何线索?

Use *before_validation*, as explained in the rails callback guide 使用* before_validation *,如rails回调指南中所述

class User < ActiveRecord::Base
  Roles = { pending: 'pending_user', role2: 'role2', etc: 'etc' }
  attr_accessible :role
  validates :role, inclusion: {in: Roles.values}
  before_validation :add_pendng_role, on: :create #Set user role to Roles[:pending]
end

您可以尝试:

before_validation :add_role, on: :create

看起来你可以改变before_createbefore_validation如果你使用:on参数:

before_validation :add_pendng_role, :on => :create

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM