Comparing time for nested associations

88 Views Asked by At

I'm in the process of building an application that'll accept a specific date from a user and which will then provide a list of events that have occurred prior to that date. While my code works if I'm looking for a specific value, I'm unable to perform a search when a particular date is passed in. Essentially i'd like to view all of the children elements that occurred previous to that particular date.

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

My transactions model is this:

class Transaction < ApplicationRecord
  belongs_to :investment


end

Investment controller

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

I'd like to only return the specific transactions that occurred before the date entered, by I'm having difficulty returning with a conditional. As you can see from the blocked out code, I'm able to successfully return entries that have a specific value. What's the appropriate way to complete the active record query with a conditional?

What's strange is that the following works:

@transactions = Transaction.where("date < ?", date)

While this doesn't:

  @investments = Investment.includes(:transactions).where("date > ?", date)

Instead I get an error message that these's no such column as "date".

Essentially what's the best way to perform this action:

  @investments = Investment.includes(:transactions).where( :transactions => {:price => 100}) 

except determining if a value is greater than or less than instead of just matching.

0

There are 0 best solutions below