ruby on rails - Checking Expense amount and expense type maximum cap -
i'm trying build small expense tracking app using rails 4.1. there expense_types model expense_name , cap. used set maximum caps gas, mobile etc. claims. expense types belong expenses model users submit. in new expense form, pick expense type drop down , add line items.
i use model method calculate total of line items. now, i'd check after every submission if total amount exceeds expense type cap. expense type stored each submission. example, if gas (expense_type_id = 2) bill submitted $100 , cap $80 i'd update notification attribute.
i'm bit confused how correctly. tried following method, got undefined method expense_type error:
def check_cap if self.expense_amount.to_i != self.expense_type.cap self.update_attribute(:notification, "this item on budget") end end
wondering how use expense_type_id check condition can me out?
your expense_type association backwards. expense should belong_to expense_type, not other way around.
use activerecord validations , errors indicate amount on cap. way record not valid , not save until valid.
check expense_amount greater cap. checking not equal mark item on budget time expense amount higher or lower cap.
class expensetype < activerecord::base has_many :expenses end class expense < activerecord::base belongs_to :expense_type validate :expense_amount_is_within_cap def expense_amount_is_within_cap if expense_amount > expense_type.cap errors.add(:expense_amount, 'is on budget') end end end
Comments
Post a Comment