Carsten
Carsten

Reputation: 1000

RoR Search conditions comparing two columns

What I basically want to do is the following:

a = Assignment.all(:conditions => { :end_date < :start_date })

I only want to select those records on which the end_date is before the start_date.

I actually don't want ending up writing a
for each, push to array if end_date is earlier than start_date.

How can I achieve this in a pretty 'Railsy'-way?

Thank you in advance.

Edit:

I think the problem is comparing the values of both columns. (Allmost) every query is comparing a cell-value to an input-value.
This is a shot in the dark, but maybe one in the right direction ?

Haven't figured out a solution.

Upvotes: 1

Views: 2398

Answers (3)

dimitarvp
dimitarvp

Reputation: 2383

It's been a while here but nevertheless, you can just use the ArelTable method:

t = Assignment.arel_table
Assignment.where(t[:end_date].lt(t[:start_date]))

The condition predicates documentation: http://www.rubydoc.info/github/rails/arel/Arel/Predications

The ArelTable documentation: http://www.rubydoc.info/github/rails/arel/Arel/Table

And a good guide: http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html

Upvotes: 1

Shotty
Shotty

Reputation: 1

try

a = Assignment.where('regioassignments.end_date < regioassignments.start_date')

use the tablename followed by the EXACT COLUMNNAMES in the database, since ActiveRecord recognizes this and uses this as SQL directly. That means the columnname for end_date is probably assignment_expected_end_date from what I figured from one of your comments.

adapted from this answer

Upvotes: 0

draxxxeus
draxxxeus

Reputation: 1523

a = Assignment.all(:conditions => ["end_date < ?", :start_date ])

Check this: http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-all

I am assuming that you are using ActiveRecord

Upvotes: 0

Related Questions