Home > OS >  Rails where method with any created_at
Rails where method with any created_at

Time:09-13

I've got function like this:

  def transfers(material, capacity, category, created_at)
    transfers_range = Transfer.first.created_at..Transfer.last.created_at if created_at.nil?
    Transfer.where(sender_dispensary_id: id, status: %i[dispatched released returned], capacity: capacity, material: material, created_at: created_at.nil? ? transfers_range : Time.given_month_range(created_at)).or(
      Transfer.where(receiver_dispensary_id: id, status: %i[dispatched released returned], capacity: capacity, material_id: material, created_at: created_at.nil? ? transfers_range : Time.given_month_range(created_at)))
  end

It's working, but is there a way to avoid query for transfer_range? I mean... If created_at == nil, then this function should skip created_at column, like it was not included in query

CodePudding user response:

When created_at is nil then transfers_range basically covers all transfers and therefore the condition is pointless and I simple would query by created_at in that case.

def transfers(material, capacity, category, created_at)
  transfers = Transfer
    .where(status: %i[dispatched released returned], capacity: capacity, material_id: material)
    .where('sender_dispensary_id = :id OR receiver_dispensary_id = :id', id: id)

  transfer = transfer.where(created_at: Time.given_month_range(created_at)) if created_at

  transfer
end

CodePudding user response:

Yes, the transfers_range query can be avoided by breaking your query into multiple lines and adding a condition on created_at presence separately. You can also combine both the OR queries into a single query like this:

def transfers(material, capacity, category, created_at)
  transfer_data = Transfer.where('sender_dispensary_id = ? OR receiver_dispensary_id = ?', id).where(status: %i[dispatched released returned], capacity: capacity, material_id: material)
  transfer_data = transfer_data.where(created_at: Time.given_month_range(created_at)) if created_at.present?
  transfer_data
end
  • Related