0

I'm not having success in this before_save callback in Rails.

    before_save :set_shot_time
    after_save :set_status

    def set_shot_time
      case :id
      when 1..24
        puts self.shot_time = "9:00 a.m."
      when 25..49
        puts self.shot_time = "9:15 a.m."
      when 50..74
        puts self.shot_time = "9:30 a.m."
      when 75..99
        puts self.shot_time = "9:45 a.m."
      when 100..124
      ...
     end    

This does not generate the desired attribute in the shot_time row of my pg database. Is it my syntax? I don't get any errors, and the log shows nothing either.

Tom Connolly
  • 674
  • 1
  • 5
  • 18

1 Answers1

2

The case statement is using the symbol :id instead of the method id and hence none of the conditions get matched. It uses the case equality operator (===) under the hood. For e.g. (1..24) === :id returns false since :id does not belong in the range. I would recommend reading this answer to gain a better understanding of the === operator. And the set_shot_time method should be run after the record is created in an after_create callback since id will be nil before the record is created.

You can remove the puts calls which I guess you added for debugging.

after_create :set_shot_time
def set_shot_time
  return if shot_time

  case id
  when 1..24
    self.shot_time = "9:00 a.m."
  when 25..49
    self.shot_time = "9:15 a.m."
  when 50..74
    self.shot_time = "9:30 a.m."
  when 75..99
    self.shot_time = "9:45 a.m."
  # ...
  end

  save!
end

Note that without the save! method call at the end, the record won't be updated.

I'm not sure if I understand the logic but you can also write it as

def set_shot_time
  return if shot_time

  self.shot_time = case id
    when 1..24
      "9:00 a.m."
    when 25..49
      "9:15 a.m."
    when 50..74
      "9:30 a.m."
    when 75..99
      "9:45 a.m."
    # ...
    end

  save!
end
Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44