ruby-on-rails - Rails 命名范围不适用于关联

标签 ruby-on-rails ruby-on-rails-4 activerecord

我有以下关联:卖家可以为每个买家定义付款方式。

我想要做的事情是这样的

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/

相关文章:

php - 使用 ActiveRecord 和 Yii2 记录实际的 SQL 查询?

ruby-on-rails - 如何处理或防止 Ruby on Rails 中的 "Only post requests are allowed"错误?

javascript - 是否可以将值从 Rails 返回到客户端 javascript?

ruby-on-rails - 为什么这个嵌套的 content_tag 不能正确呈现?

ruby-on-rails - 在 Heroku、PostgreSQL 和 Rails 5 上运行迁移时出错

mysql - 创建一个可以动态创建新表单/数据库表的 Rails 应用程序?

ruby-on-rails - 将 Activerecord 数据库迁移到 Mongoid

ruby-on-rails - 在定义可为空字段和外键时在 Rails 中搭建脚手架

ruby-on-rails - 如何在 erb 文件中渲染嵌套集合 - ruby​​ on Rails

ruby-on-rails - Rails 中的动态命名空间 Controller