ruby - 比较嵌套关联的时间
问题描述
我正在构建一个应用程序,该应用程序将接受用户的特定日期,然后提供在该日期之前发生的事件列表。虽然如果我正在寻找一个特定的值,我的代码可以工作,但在传入特定日期时我无法执行搜索。基本上我想查看在该特定日期之前发生的所有子元素。
My Investments models is this:
class Investment < ApplicationRecord
has_many :transactions
def count
final_quanity = 0
self.transactions.each do |transaction|
final_quanity+= transaction.quantity
end
final_quanity
end
def average_price
total_spent = 0
self.transactions.each do |transaction|
total_spent += transaction.price
end
total_spent
end
end
我的交易模型是这样的:
class Transaction < ApplicationRecord
belongs_to :investment
end
投资控制人
class InvestmentsController < ApplicationController
def index
if params[:date]
# @investments = Investment.includes(:transactions).where(transactions: {quantity:10})
@investments = Investment.includes(:transactions).where("date > ?", params[:date])
else
@investments = Investment.all
end
render json: @investments
end
end
我只想返回在输入日期之前发生的特定交易,因为我很难有条件返回。正如您从被屏蔽的代码中看到的那样,我能够成功返回具有特定值的条目。使用条件完成活动记录查询的适当方法是什么?
奇怪的是以下工作:
@transactions = Transaction.where("date < ?", date)
虽然这不是:
@investments = Investment.includes(:transactions).where("date > ?", date)
相反,我收到一条错误消息,指出这些列没有“日期”之类的列。
基本上执行此操作的最佳方式是什么:
@investments = Investment.includes(:transactions).where( :transactions => {:price => 100})
除了确定一个值是大于还是小于而不是仅仅匹配。
解决方案
推荐阅读
- php - 使用日期时间比较两个自定义日期字段中的月份
- python - 在 Python 中,我如何从文件中读取值并将它们放入 RawArray?
- html - 单击按钮时如何隐藏文本
- hive - Hive - where 子句中的多个子查询失败
- python - 将可变数量的列传递给 Pyspark .Agg()
- c - 如何检查文件是否写入成功?
- pdf - ghostscript pdf 到 postscript 的转换需要很长时间
- reactjs - 如何在 React 中将结果数据从一个页面发送到另一个页面
- javascript - React Native - 如何使用本地化和 react-navigation 来跨屏幕访问翻译?
- ios - Swift 在 iOS 模拟器中使用 AVAudioEngine 托管 AUv3 崩溃