我有三个模型: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
任何提示?
答案 0 :(得分:0)
创建范围
scope :available, where(:current => true).joins(:transactions)
现在你可以说
user.owned_products.available
未经测试。但这会让你知道如何继续前进。
Here是范围的参考。