0

UserProductおよびの 3 つのモデルがあり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

これは可能ですか?そうでない場合は、 and のような関連付けリンクuser.available_productsuser.lended_products行いますが、次のように、3 番目のモデルで関連付けを行うには両方のモデルの条件を使用する必要があるため、方法がわかりません。

アプリ/モデル/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 に答える