【问题标题】:Custom method or association for chained model associations链式模型关联的自定义方法或关联
【发布时间】:2014-06-30 04:48:47
【问题描述】:

我有三个模型:UserProductTransaction

以下是关联:

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_productsuser.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


    【解决方案1】:

    创建范围

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

    现在你可以说

    user.owned_products.available
    

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

    Here 是作用域的参考。

    【讨论】:

    • 谢谢。很抱歉,它不起作用:-(我已经阅读了有关范围的 Rails 指南,但是示例很少,而且我不太了解。否则,您认为我应该删除我的一些 @ 987654324@ 关联,以便用scopes 替换它们?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多