通过关联作用域:加入和合并 [英] scope through associations : joins and merge

查看:48
本文介绍了通过关联作用域:加入和合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型:UserProductTransaction.(Transaction属于两者,User有很多ProductProduct有很多User, 通过 Transaction)

I have three models : User, Product and Transaction. (Transaction belongs_to both, and User has many Product and Product has many User, through Transaction)

在我的 Transaction 模型中,我有一个 current 交易的范围:

In my Transaction model, I have a scope for current transactions :

scope :current, -> { where 'transactions.start_date IS NOT NULL AND transactions.end_date IS NULL' }

我希望能够在控制台中执行此操作,以便检索具有 current 交易的所有产品:

I want to be able to do that in the console, in order to retrieve all the products that have a current transaction :

User.first.products.owned

在控制台中,我可以使用:

In the console, I can make it happen with :

User.first.products.merge(Transaction.current.ownership)

第一次尝试

所以我将它添加到我的 Product 模型中:

def self.owned
  merge(Transaction.current.ownership)
end

我在控制台输入:

User.first.products.owned

但是 Rails 控制台告诉我的是什么:

But here what's rails console tells me :

NoMethodError: undefined method `merge' for #<Class:0x00000004e2c0f8>
    from /home/flo/.rvm/gems/ruby-2.0.0-p195/gems/activerecord-4.0.0.rc1/lib/active_record/dynamic_matchers.rb:22:in `method_missing'

其他尝试

如果我将它添加到我的 Product 模型中:

def self.owned
  joins(:transactions).merge(Transaction.current.ownership)
end

我在控制台输入:

User.first.products.owned

但它检索当前交易的所有产品,而不仅仅是当前交易的第一个用户的产品.

But it retrieve all products with a current transaction, and not only the first user's products with a current transaction.

你知道我做错了什么吗?

Do you have any idea of what I'm doing wrong ?

推荐答案

因为您只是没有订购或限制您的产品.

Of cause you just didnt oder or limit your products.

scope :current, where('transactions.start_date IS NOT NULL AND transactions.end_date IS NULL').order("by whatever").limit(1)

您可能需要订购正确的产品,否则您可以删除订购方法.

You may need to order it the right product is selected if not you can remove the order method.

这篇关于通过关联作用域:加入和合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆