user1000232
user1000232

Reputation: 219

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?

Upvotes: 0

Views: 310

Answers (3)

michaelrshannon
michaelrshannon

Reputation: 524

Looks like you'll be able to change before_create to before_validation if you use the :on argument:

before_validation :add_pendng_role, :on => :create

Upvotes: 1

Robin
Robin

Reputation: 21884

You could try:

before_validation :add_role, on: :create

Upvotes: 2

rorra
rorra

Reputation: 9693

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

Upvotes: 2

Related Questions