mvanio
mvanio

Reputation: 505

How to search Spree::Orders and associations with ransack gem

Using Spree and ransack, how is it possible to return the Spree::Variants included in Spree::Orders that have completed since a certain date? The ransack documentation gives a little advice about searching associations, but does not seem to go deep enough.

Spree::Order
  has_many :line_items

Spree::LineItem
  belongs_to :line_item
  belongs_to :variant 

Spree::Variant
  has_many: line_items

Orders that have completed can be searched with:

  o=Spree::Order.complete.ransack(completed_at_gt: '2015-05-01')

But how to find the Spree::LineItems within these orders and return the Spree::Variants' SKUs within these orders is unclear.

I'm attempting to use ransack because this will be used in a Spree report.

Upvotes: 3

Views: 811

Answers (1)

gmacdougall
gmacdougall

Reputation: 4911

You don't need to use ransack in this area at all. ActiveRecord will let you do what you need:

Spree::Order.complete.where(
  Spree::Order.arel_table[:completed_at].gteq(
    Date.new(2015, 10, 1)
  )
).joins(
  line_items: :variant
).select(:sku).distinct.pluck(:sku)

If you must use ransack, you can get the ActiveRecord relation, using .result and apply the joins and such.

Spree::Order.complete.ransack(
  completed_at_gt: '2015-05-01'
).result.joins(
  line_items: :variant
).select(:sku).distinct.pluck(:sku)

Since you don't have .pluck, you're running a really old version of Spree that is pre-Rails 4. You can get the results by using:

Spree::Order.complete.ransack(
  completed_at_gt: '2015-05-01'
).result.joins(
  line_items: :variant
).select(:sku).map(&:sku).uniq

Upvotes: 2

Related Questions