oop - Understanding method calls in ruby -


i have 2 classes

class cart   belongs_to :coupon end  class coupon   has_many :carts    def discount   end end 

i execute

cart = cart.last.coupon.discount 

how can know cart within discount method without passing cart parameter?

you can't coupon. i'd suggest delegate discount within cart.

class cart   belongs_to :coupon   delegate :discount, to: coupon end  class coupon   has_many :carts    def discount   end end 

then can

discount = cart.discount 

however, note delegate rails method. assume that, using belongs_to , tagged ruby-on-rails, within rails. if not, work:

class cart   belongs_to :coupon    def discount     coupon.discount if coupon   end end 

Comments