I have two tables/models (User and Holiday). A user has a set number of holidays. In the Holiday model, a user can book a number of holidays (integer).
1) John has a total 10 holiday credit
2) John books 4 holidays
Result: John has 6 holidays left
I know it has something to do with adding a method in User and passing the holidays taken into it.
How do I go about deducting the holidays booked from the holiday credit?
In the in User model:
# assuming, you have a method `holidays_booked`, # that returns the number of booked holidays def holidays_left 10 - holidays_booked end
If each user has a
holiday property/field, then through associations between the two tables the value can be calculated.
When setting up the database a default value for the holiday credit can be defined. For example:
If you are adding a column to hold the value:
add_column :users, :holiday_credit, :integer, :default => 10
Now every user will have a default holiday credit in your database. This could also be done at object creation time during the object's initialization.
To update the value, a method within the User model can be written like so:
class User < ActiveRecord::Base def calculate_holiday_credits self.holiday_credit = default_value - Holiday.find(self.id).count end end
The function can be modified to accommodate your needs, but I hope this gives you the general idea.
In short, you want to search in the other table the number of times the id for the user model shows up and carry out your calculation with the results.
The booking mechanism would be sort of the inverse of this. In the holiday table, you want to make a method that creates an entry in the database with the user who booked the holiday, so that when the user runs the method detailed above, the value is update appropriately.