Search code examples
ruby-on-railsvalidationruby-on-rails-4attr-accessor

Conditional validation in rails using attr_accessor


I'm attempting to do some conditional validation in my model Company. Basically the idea is that Company is used by a lot of different controllers, each with their own validation requirements. My thought was to use attr_accessor to add an attribute that identifies the controller in question like so:

<%= company.hidden_field :controller_context, value: "incorporation" %>

However, I've been unable to use :controller_context as a condition in my validation.

validate :final_incorporation, if: "controller_context=='incorporation'"

The above gives me no errors but does not trigger validation either. However, if I try to get the value of controller_context in my log with the following:

logger.debug "controller_context: #{controller_context}"

I get the error

undefined local variable or method `controller_context' 

I've been looking around on google for a solution. I've seen one recommendation to edit my controller to accommodate this but this doesn't seem optimal for a variety of reasons. What might I be missing here?

Thanks in advance.


Solution

  • Your initial idea seems practical. I'm not entirely sure if the value of your hidden field is available in the model. Try it like this and let me know how it goes:

    Add attr_accessor :controller_context to your model. In your controller, before calling save, assign your controller's name to @company.controller_context.

    Then while validating in the model add a condition, like: validate :final_incorporation, if: :is_incorporation

    And in the method:

    def is_incorporation?
      controller_context == 'incorporation'
    end