0

我有三个模型UserProductTransaction

以下是关联:

应用程序/模型/transaction.rb

# A transaction has a `current` boolean that is true when the transaction is currently happening, and nil else.

belongs_to :seeker, class_name: "User", foreign_key: "seeker_id"
belongs_to :product  

应用程序/模型/user.rb

has_many :owned_products, class_name: "Product",
                          foreign_key: "owner_id",
                          dependent: :destroy
has_many :transactions, foreign_key: "seeker_id",
                        dependent: :destroy
has_many :requested_products, through: :transactions, source: :product
has_many :active_transactions, -> { where current: true },
                               class_name: 'Transaction',
                               foreign_key: "seeker_id"
has_many :borrowed_products, through: :active_transactions, source: :product

应用程序/模型/product.rb

belongs_to :owner, class_name: "User",
                   foreign_key: "owner_id"
has_many :transactions, dependent: :destroy
has_many :seekers, through: :transactions,
                     source: :seeker  
has_one :active_transaction, -> { where current: true },
                             class_name: 'Transaction'
has_one :borrower, through: :active_transaction,
                            source: :seeker

我想创建一个允许我执行以下操作的方法:

user.owned_products.available # returns every product owned by the user that has a transaction with current:true.
user.owned_products.lended # returns every product owned by the user that has no transaction with current.true

这可能吗 ?如果没有,我会做一个关联链接user.available_productsuser.lended_products但我不知道如何,因为我必须使用两个模型中的条件才能在第三个模型中建立关联,如下所示:

应用程序/模型/user.rb

has_many :available_products, -> { where borrower: nil },
                              class_name: "Product",
                              foreign_key: "owner_id"

我收到此错误消息:

ActionView::Template::Error:
   SQLite3::SQLException: no such column: products.borrower: SELECT COUNT(*) FROM "products"  WHERE "products"."owner_id" = ? AND "products"."borrower" IS NULL

有什么提示吗?

4

1 回答 1

0

创建范围

scope :available, where(:current => true).joins(:transactions)

现在你可以说

user.owned_products.available

这未经测试。但这会让你知道如何继续前进。

是范围的参考。

于 2013-06-13T13:42:55.863 回答