Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何创建跨模型3级的活动记录搜索?_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 如何创建跨模型3级的活动记录搜索?

Ruby on rails 如何创建跨模型3级的活动记录搜索?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,好吧,数据库是我rails的弱点 我有3个模型,我正在尝试搜索:用户,发票,付款 用户有多张发票,发票有多笔付款 我正在尝试创建一个搜索,该搜索将查找给定日期范围内当前用户的所有付款 到目前为止,我就是这样做的 invoices = current_user.invoices payments = invoices.inject([]) {|arr,x| arr += x.payments.where("payment_date <= ? and payment_date >= ?"

好吧,数据库是我rails的弱点

我有3个模型,我正在尝试搜索:用户,发票,付款

用户有多张发票,发票有多笔付款

我正在尝试创建一个搜索,该搜索将查找给定日期范围内当前用户的所有付款

到目前为止,我就是这样做的

invoices = current_user.invoices
payments = invoices.inject([]) {|arr,x| arr += x.payments.where("payment_date <= ? and payment_date >= ?", '2011-02-01', '2011-01-01')}
invoices=当前用户发票
付款=发票。注入([]){| arr,x | arr+=x.payments。其中(“付款日期=?”,'2011-02-01','2011-01-01'))

我觉得这很疯狂。我确信一定有一种方法可以直接从数据库中获取这些信息,而无需遍历结果。有什么想法吗?提前干杯

您应该使用以下内容:

Payments.joins(:invoice => :user).where("users.id = ? AND (payments.payment_date <= ? and payments.payment_date >= ?)", current_user.id, '2011-02-01', '2011-01-01')
更新2,另一个解决方案:

在您的型号
用户中

has_many :payments, :through => :invoices
要执行查询,请执行以下操作:

time_range = (Time.now.midnight - 1.month)..Time.now.midnight
current_user.payments.where(:payment_date => time_range)

您应该使用以下内容:

Payments.joins(:invoice => :user).where("users.id = ? AND (payments.payment_date <= ? and payments.payment_date >= ?)", current_user.id, '2011-02-01', '2011-01-01')
更新2,另一个解决方案:

在您的型号
用户中

has_many :payments, :through => :invoices
要执行查询,请执行以下操作:

time_range = (Time.now.midnight - 1.month)..Time.now.midnight
current_user.payments.where(:payment_date => time_range)

很好,我用了你的最终解决方案。我还没有真正理解连接,所以必须做更多的阅读(尽管我意识到最终的解决方案是在引擎盖下做的)。谢谢。我建议你也读一下关于尼斯的书,我用了你的最终解决方案。我还没有真正理解连接,所以必须做更多的阅读(尽管我意识到最终的解决方案是在引擎盖下做的)。谢谢。我建议你也读一下