0

Still newish to Rails, so apologies, I've been looking online and can't seem to find something that works.

I have an application where a guest can RSVP to an event. On creation of the guest I'm defaulting the :rsvp attribute to 'Awaiting RSVP'. I want to validate from my model that the value of this attribute can only be one of the below values:

  • Awaiting RSVP
  • Attending
  • Not Attending

This is the code in my model currently:

class Guest < ApplicationRecord
  after_initialize :set_defaults

  validates :name, presence: true
  validate :check_rsvp?

  private

  def set_defaults
    self.rsvp = "Awaiting RSVP"
  end

  def check_rsvp?
    self.rsvp == "Awaiting RSVP" || "Attending" || "Not Attending"
    # errors.add(:rsvp, "can't equal the value provided") if rsvp != "Awaiting RSVP" || "Attending" || "Not Attending"
  end
end

I've then got a test to check this is working, however I get this error:

Guest rsvp can only equal 'Awaiting RSVP', 'Attending' or 'Not Attending'
     Failure/Error: expect(@guest).not_to be_valid
       expected #<Guest id: 1, name: "Dan", email: nil, rsvp: "aaaa", unique_code: nil, created_at: "2017-07-02 11:00:17", updated_at: "2017-07-02 11:00:17"> not to be valid

If I replace the code in check_rsvp? with the line that is commented out, the above test passes but all the other fail

Guest is valid
     Failure/Error: expect(@guest).to be_valid
       expected #<Guest id: nil, name: "Dan", email: nil, rsvp: "Awaiting RSVP", unique_code: nil, created_at: nil, updated_at: nil> to be valid, but got errors: Rsvp can't equal the value provided

Where am I going wrong?

DanBonehill
  • 145
  • 1
  • 7

1 Answers1

1

I'd suggest you use enum it has already some helper methods and validations more detail in DOCS

enum rsvp: { awaiting: 0, attending: 1, not_attending: 2 }

and default value set via DB defaults

Oleh Sobchuk
  • 3,612
  • 2
  • 25
  • 41