4

Lets say we have following table:
Employee
ID Name Sick_Leaves Casual_Leaves
1 John 4 8
2 Nancy 5 2
3 Matthew 2 9

Now if I want to get a list of all the Employess who have taken more sick leaves than casual, its straight forward in SQL:
Select * from Employee Where Sick_Leaves > Casual_Leave

Now considering that I have a Rails Active Record Model class defined for Employee, how can I execute the same query using model class itself ? I am getting stuck in how to define the WHERE clause. If it had been Sick_Leaves > 5 (or some fixed number), then its simple, but what now when we want to compare two columns itself ?

Any help will be appreciated.

2 Answers 2

5

You can use the following ActiveRecord query:

Employee.where('sick_leaves > casual_leaves')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But I would prefer a solution in which I dont use a hand written SQL.
4

Rails' interface to Active Relation doesn't have a simple syntax for expressing "greater than" (amongst other things). So you can either use hand-written SQL (as @JKen12579 suggested) or you can step down into the bowels of using ARel syntax. (It's weird at first but gives you the full power of SQL still.)

Employee.where(arel_table[:Sick_Leaves].gt(arel_table[:Casual_Leaves]))

I'd recommend this approach because it keeps you writing Ruby code, it alleviates issues with having to write the table name or not (e.g. "Do I need to use employees.<column>?"), and it is database agnostic (which may not be important here but maybe later... so get used to the syntax and never worry).

6 Comments

Ok, lets say if I relax the requirement of greater than, i.e. we need sick_leaves = casual_leaves, then can we do that through code rather than hard coding column names ?
Would have to do the same as above but with .eq() instead of .gt().
Am I missing something? This is doing it through code. Are you looking to do this in a Ruby array? Such as my_arary.select { |e| e.sick_leaves > e.casual_leaves }? Or are you wanting a SQL/database query still?
Nope, this sounds good. I did not know about ARel syntax. May be this would help me here. Actually I want to do this on an INNER JOIN result where first column is from first table and second column to compare is from other table which is being joined.
You may appreciate this talk from Rails Conf: youtube.com/watch?v=ShPAxNcLm3o
|

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.