我有以下关联:卖家可以为每个买家定义付款方式。
我想要做的事情是这样的
a_seller = Seller.find(34)
a_buyer = Buyer.find(22)
a_buyer.payment_methods_for_seller a_seller
简单,我想:
class SellerBuyerPaymentMethod < ActiveRecord::Base
belongs_to :buyer
belongs_to :seller
end
class Buyer < ActiveRecord::Base
has_many :seller_buyer_payment_methods
scope :payment_methods_for_seller, ->(seller) { joins(:seller_buyer_payment_methods).where(:seller => seller) }
end
但我收到错误
NoMethodError: undefined method `payment_methods_for_seller' for Buyer:0x000001028e6d88
这有效:
class Buyer < ActiveRecord::Base
has_many :seller_buyer_payment_methods
def payment_methods_for_seller seller
SellerBuyerPaymentMethod.where( :buyer => self, :seller => seller )
end
end
但我觉得我应该能够用范围来做到这一点。我在这里缺少一些简单的东西。非常感谢任何帮助...
Rails 4.1、Ruby 1.9.3
最佳答案
Rails 作用域只是类方法。内部 Active Record 将范围转换为类方法。因此,当您定义此范围时:
scope :payment_methods_for_seller, ->(seller) { joins(:seller_buyer_payment_methods).where(:seller => seller) }
您可以将此 payment_methods_for_seller
方法视为 Buyer
类的类方法。这就是您收到此错误的原因:
NoMethodError: undefined method `payment_methods_for_seller' for Buyer:0x000001028e6d88
当您调用 Buyer
类的对象上的类方法时:
a_buyer.payment_methods_for_seller a_seller
您不能在类的对象上调用作用域/类方法。您可以在类本身上调用它:
Buyer.payment_methods_for_seller
第二个示例之所以有效,是因为在这种情况下,您将 payment_methods_for_seller
方法定义为 Buyer
类的实例方法。
希望这能消除您的困惑。
您可以通过 seller_buyer_methods 关联获取相关记录,而不是使用范围:
a_buyer.seller_buyer_payment_methods.where( :seller => a_seller )
这是一篇关于 Active Record scopes vs class methods 的精彩博客文章这将为您提供有关该主题的一些更有趣的信息。
关于ruby-on-rails - Rails 命名范围不适用于关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948292/