user2012677
user2012677

Reputation: 5745

How to validate only certain instances of a rails model

What is wrong with my model that I can't see the #black? method?

Error:

undefined method `black?' for Car:Class

Car Modal

  # frozen_string_literal: true

  class Cars < Base

    if black?
      validates :style, presence: true
    end

    private

    def black?
     color_options.include?("black")
    end

  end

If I do...

validates :style, presence: true, if: :seller?

The code works, but I plan on adding many more validations in the if statement block, so it would be nice to get the if statement block (if end) working.

Upvotes: 0

Views: 462

Answers (1)

Chris Heald
Chris Heald

Reputation: 62668

You're calling black? on the class, not on an instance of the class. At the point that your if black? code is called, self evaluates to Cars! It wouldn't make any sense to call Cars.black? - you want to know if a single instance of the car is black!

It is good practice to wrap all your various validation conditions into a single predicate which you then reference with the :if syntax.

For example, if you had a complex set of conditions, you might set up a validator:

class Cars
  validates :style, presence: true, if: :validate_style?

  private

  def validate_style?
    color_options.include?("black") ||
      wheel_options.include?("premium") ||
      Time.now.wday == 3
  end
end

Upvotes: 4

Related Questions