0
array = [#<Product id: 206, product: "first product", created_at: "2018-05-28 09:50:26", updated_at: "2018-05-28 09:50:26">, #<Product id: 207, product: "second product" ,created_at: "2018-05-28 09:50:46", updated_at: "2018-05-28 09:50:46"]

params[:from_date] = "2018-04-28 09:50:26"

params[:to_date] = "2018-05-28 09:50:46"

I'm filtering the above array with the following params (params[:from_date], params[:to_date]) using the below select statement.

array.select { |product| product.created_at >= params[:from_date] && product.created_at <= params[:to_date] }

I think there are more efficient methods than the above.

Are there any other methods to tackle this issue in a more efficient way?

4
  • I think it's perfect Commented May 28, 2018 at 11:07
  • (params[:from_date]..params[:to_date]).cover? product.created_at Commented May 28, 2018 at 11:22
  • @mudasobwa its working fine, how cover? is different from include? Commented May 28, 2018 at 11:43
  • Range#include? performs additional checks for whether the range is integer (click on “view source”.) Commented May 28, 2018 at 11:48

1 Answer 1

1

Have you thought of improving the SQL query? It looks like your array contains the Products that are result from a query like Product.all. Maybe you can change that to something like:

Product.where("created_at >= :from_date AND created_at <= :to_date",
  {from_date: params[:from_date], to_date: params[:to_date]})

I think that is more efficient approach because you will improve your app performance. And from my point of view the code looks more understandable this way.

Sign up to request clarification or add additional context in comments.

2 Comments

can't do that, because product is not coming from Product.all, It's coming from `@page_instance.users.includes(:products).map(&:products), end result will be array anyway
then you can instead of doing an include, change it for a join like this @page_instance.users.joins(:products).where(...) and do the filter there. if you really need the complete array first and then filter, the solution that you have at the moment is the one to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.