Hi,
I have the following two methods in my class:
def self.decrease_credits(amount, user_id)
user = User.find(user_id)
company = Company.find(user.company_id)
credits_new_saldo = company.credits - amount
company.update_attribute(:credits, credits_new_saldo)
end
def self.available_credits(user_id)
user = User.find(user_id)
company = Company.find(user.company_id)
return company.credits
end
They both work, but since the code of the second method is the same as
the first three lines of the method self.decrease_credits, I would like
to rewrite it as:
def self.decrease_credits(amount, user_id)
credits_new_saldo = available_credits(user_id) - amount
company.update_attribute(:credits, credits_new_saldo)
end
But then I get the error that available_credits is not known in the
class. Why is this not working and what is the right way? All help is
greatly appreciated. Thanks.
Kind regards,
Nick
Hi Andreas,
thanks for your help. Really, really helpful. Too complicated you say,
well and I thought I was doing it the simple way! Thanks for pointing me
to instance methods, a piece of Rails I will be exploring and definitely
using more and more in the future. It is really ridiculously easy, wow!
Thanks.
Nick
Andreas S. wrote:
But all of this seems way too complicated. Why don’t you use instance
methods?
class User
def available_credits
self.company.credits
end
def decrease_credits(amount)
credits_new_saldo = self.available_credits - amount
self.company.update_attribute(:credits, credits_new_saldo)
end
end
Andreas S. wrote:
Nick S. wrote:
They both work, but since the code of the second method is the same as
the first three lines of the method self.decrease_credits, I would like
to rewrite it as:
def self.decrease_credits(amount, user_id)
credits_new_saldo = available_credits(user_id) - amount
self.available_credits(user_id)
That’s wrong, it should be:
self.class.available_credits(user_id)
Nick S. wrote:
Hi,
I have the following two methods in my class:
def self.decrease_credits(amount, user_id)
user = User.find(user_id)
company = Company.find(user.company_id)
Why not “company = user.company”?
They both work, but since the code of the second method is the same as
the first three lines of the method self.decrease_credits, I would like
to rewrite it as:
def self.decrease_credits(amount, user_id)
credits_new_saldo = available_credits(user_id) - amount
self.available_credits(user_id)
But all of this seems way too complicated. Why don’t you use instance
methods?
class User
def available_credits
self.company.credits
end
def decrease_credits(amount)
credits_new_saldo = self.available_credits - amount
self.company.update_attribute(:credits, credits_new_saldo)
end
end