0

I have a model that can be edited by two different types of users. The first has a login and has special privileges (let's call them a 'user'). The second is just some random user without a login with limited privileges (let's call them a 'guest').

The guest only really interacts with the model through one controller and we want certain validations to only apply in this case. The validations we want to apply exist within a module.

I tried doing something like this in the controller action, but it didn't seem to work:

@object = Model.find(params[:object_id])
@object.extend SpecialValidations

Then we would check for the objects validity (maybe directly or when updating attributes) and then display any errors generated by the validations.

Is there a better way to do this?

Thanks!

Chris Butler
  • 733
  • 6
  • 23

2 Answers2

1

One alternative is to include the following in your Model:

attr_accessor :guest

def run_special_validations?
    guest
end

validate :special_validation1, if: run_special_validations?
validate :special_validation2, if: run_special_validations?

Then, by having the controller set @object.guest = true, you will tell the object to run the conditional validations.

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33
0

You could keep the validation without any conditions, and just skip it in the user controller (by using the update_attribute method, for example).

Henrique Zambon
  • 1,301
  • 1
  • 11
  • 20