I
I
Ivan Nesterovich2014-06-02 11:30:54
Ruby on Rails
Ivan Nesterovich, 2014-06-02 11:30:54

[RoR] How to organize iteration in the scope of the where method?

scope :with_size_ids, lambda { |size_ids|
    sizes = Catalog::Size.find(size_ids)
    sizes.map do |size|
      where('product.size >= ? AND product.size <= ? ', size.max_from, size.max_to)
    end
  }

There is a size base that sets the range of numbers (from and to). As input, the scope receives an array of id's of these sizes. The output should be a selection of records suitable for these sizes.
As a result, the request should be similar to this:
where('product.size >= ? AND product.size <= ? ', 0, 100).where('product.size >= ? AND product.size <= ? ', 200, 300) # И так далее

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimitriy, 2014-06-02
@vanderv

It is possible like this:

scope :with_size_ids, lambda { |size_ids|
  sizes = Catalog::Size.where(id: size_ids).pluck(:max_from, :max_to)
  ranges = sizes.inject([]){|o, i| o << Range.new(*i)}
  where(size: ranges)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question