我有三个模型User
:Product
和Transaction
。
以下是关联:
应用程序/模型/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_products
,user.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
有什么提示吗?