ruby - 了解 ruby​​ 中的方法调用

标签 ruby oop ruby-on-rails-4

我有两个类(class)

class Cart
  belongs_to :coupon
end

class Coupon
  has_many :carts

  def discount
  end
end

我执行

cart = Cart.last.coupon.discount

如果不将购物车作为参数传递,我如何知道折扣方法中的购物车是哪个?

最佳答案

那将是我的方法:

class Cart
  belongs_to :coupon

  def discount
    coupon.discount(self) unless coupon.nil?
  end
end

class Coupon
  has_many :carts

  def discount(cart)
    # use the coupon discount logic to apply discount on particular cart
  end
end

关于ruby - 了解 ruby​​ 中的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469668/

相关文章:

ruby - vim 使用 AutoComplPop 插件崩溃

PHP 在同一类的实例之间共享 protected 属性

r - 扩展 R S4 对象以具有新插槽并保持原始对象以相同方式工作

ruby-on-rails - 出于性能考虑,我应该使用 `.blank?` 吗?

ruby-on-rails - 在 Ruby on Rails 中如何通过键访问对象的 (ActiveRecord::Relation) 值?

ruby-on-rails - 无法加载 lib 目录模块 - 未初始化的常量 - rails 2 到 rails 3 升级

ruby-on-rails - 为什么 Ruby Array 类有 to_a 和 to_ary 方法?

javascript - Ruby on Rails 4.0 + javascript 未加载

ruby - 在 neo4j.rb 中使用 has_many "both"

java - 为什么我无法调用代码中的任何方法?