Home > Software design >  Where comparison on join table with buffer value on rails
Where comparison on join table with buffer value on rails

Time:10-19

How can I use the join table's column value with arithmetic operation during the where condition on Rails?

User and Order are the two Schema, Order has user via Foreign key relation

My goal is to find if an Order was created/placed within 5 minutes of User creation (Understanding Users who signup for placing an Order)

Tried the following queries

Order.where('country': 'US').joins(:user).where('orders.created_at <= :u_date', {u_date: 'users.created_at' 5.minutes })

With this query we get the following error no implicit conversion of Time into String, so the users.created_at is not evaluating into a Date

Hence tried converting the string to DateTime objects, which failed too

Order.joins(:user).where('orders.created_at < ?', 'users.created_at' 5.minutes)

How can I do the comparison inside the Where query? Right now I am plucking the data and comparing it, It'd be great to make it work inside the Where or any relevant query itself

CodePudding user response:

You're invoking on a string passing as argument a Time object, which is not an out-of-the-box operation, at least in Rails.

If the time to add is not dynamic you could try;

where("orders.created_at <= users.created_at   INTERVAL '5.minutes'")

which makes your DBMS add the proper interval to users.created_at (in this case I'm assuming Postgresql)

  • Related