Search code examples
ruby-on-railsmodulecontrollerextendmixins

Apply validation module to model in certain controllers only


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!


Solution

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