-2

I am trying to implement a lambda within a where() method in an ActiveRecord on Rails. Here is my code:

 @applications.where { |app| !((calculate_days_ago(app.shipping_date) >= 10 && calculate_days_ago(:app.shipping_date) <= 19) || app.followup_calls.count == 0) }

Where @applications is an ActiveRecord (e.g. Application.all). But when I am trying to access it (e.g. order, where), it's type is change to WhereChain and I am having an exception:

undefined method `where' for #ActiveRecord::QueryMethods::WhereChain:0x6fb1000>

Is there a way I can implement a lambda expression on my where() condition with the proper return type?

Note: I came from a C# background and such lambda can be done like that, I am a newbie on Ruby on Rails. I am not aware that this community bash newbies with downvotes. I tried my best to make my question as clear as possible.

John Isaiah Carmona
  • 5,260
  • 10
  • 45
  • 79

1 Answers1

3

The where method doesn't take (or at least it won't use) any block passed to it. If you want to filter based on arbitrary ruby code, then use

@applications.select {|app| !((calculate_days_ago(app.shipping_date) >= 10 && calculate_days_ago(:app.shipping_date) <= 19) || app.followup_calls.count == 0) }

Be aware though that this fetches all the rows matching any previous conditions on the scope, creates active record objects from them and then filters them - if possibly it will in general be a lot faster to rewrite this to use where e.g.

@applications.where(:shipping_date => (19.days.ago .. 10.days.ago))

In addition this keeps things as a relation so you can continue to chain extra where, order etc. calls.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Thanks, but the `select` return an `Array` and I am unable to use `where` on it. Does your second example translate to "Shipping Date is between 10 to 19 days ago"? – John Isaiah Carmona Feb 23 '15 at 09:58
  • @john It does indeed. – Frederick Cheung Feb 23 '15 at 10:00
  • Many thanks! Do you know a way to implement my second condition (`app.followup_calls.count == 0`)? I have a one-to-many relationship to the `followup_calls` table and I need to know if it has no followup-call? – John Isaiah Carmona Feb 23 '15 at 10:03
  • @john either use a counter cache on the association (so that there is just an integer column you can filter on) or a left join. Lots of questions here about that specific type of query – Frederick Cheung Feb 23 '15 at 11:07