首页 > 解决方案 > 比较嵌套关联的时间

问题描述

我正在构建一个应用程序,该应用程序将接受用户的特定日期,然后提供在该日期之前发生的事件列表。虽然如果我正在寻找一个特定的值,我的代码可以工作,但在传入特定日期时我无法执行搜索。基本上我想查看在该特定日期之前发生的所有子元素。

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}) 

除了确定一个值是大于还是小于而不是仅仅匹配。

标签: rubycomparisonnested-includes

解决方案


推荐阅读