0

I have two models interacting with one another. Each Course has_many Reservations, upon saving the reservation I want to update the Course :course_places attribute to minus the number of reservations that have just been made (equal to the remaining_places method I have created in the reservation controller). I hope that makes sense.

I have been trying to use this answer as inspiration but its not working because the Course update_places! method doesn't know which reservation it's referring to https://stackoverflow.com/a/19169367/6103550

Any suggestions would be warmly received! thanks

Error

undefined method `reservation' for #<Course:0x007f832c1f5020> Did you mean? reservations reservations=

Course Model

class Course < ApplicationRecord
  belongs_to :listing, optional: true
  has_many :reservations

  def update_places!
    self.update_column(:course_places, self.reservation.sum(:remaining_places))
  end
end

Reservation Model

class Reservation < ApplicationRecord
  belongs_to :user
  belongs_to :course
  belongs_to :listing

  after_save :update_course_places

  def update_course_places
    self.course.update_places!
  end

end
Jack Riminton
  • 130
  • 1
  • 8

1 Answers1

0

Hope this works

def update_places!
  remaining_places = Reservation.where(course_id: self.id).sum(:remaining_places)
  self.update_column(:course_places, remaining_places)
end
Narasimha Reddy - Geeker
  • 3,510
  • 2
  • 18
  • 23
  • Almost! I might need to think about what's happening here. So with a course with 10 places on it, I made one reservation, now it has 16. It seems to be doubling the reservation number, taking it from the original course places and then doubling that?! I will try with other numbers – Jack Riminton Oct 31 '17 at 13:12
  • May i know your requirement? When exactly you need to minus remaining_places? – Narasimha Reddy - Geeker Oct 31 '17 at 13:16
  • Well actually it is working! I tried creating a new course and doing a reservation with that and it is working perfectly. Thanks very much. Not sure what's going on with the old courses – Jack Riminton Oct 31 '17 at 13:16
  • Oh it's might be data issue. Cool – Narasimha Reddy - Geeker Oct 31 '17 at 13:18