【发布时间】:2014-06-30 04:48:47
【问题描述】:
我有三个模型:User、Product 和 Transaction。
以下是关联:
app/models/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
app/models/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
app/models/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 这样的关联链接,但我不知道怎么做,因为我必须使用两个模型的条件才能在第三个模型中建立关联,如下所示:
app/models/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
有什么提示吗?
【问题讨论】:
标签: ruby-on-rails ruby model-associations