简体   繁体   中英

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. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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