Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing one attribute to another with ransack

Ransack allows me to build conditions with an attribute, a predicate and a value. I haven't been able to find any documentation on how to compare one attribute to another however. For instance, how could I create a condition for:

WHERE column_a < column_b
like image 748
Dave Avatar asked Nov 01 '22 21:11

Dave


1 Answers

I've been using Ransack for quite a while, but I don't see any possibility to do what you are looking for. What you want is a "case -> when" statement, which can be produced in Rails or as SQL with ActiveRecord.

Ransack gives you the ability to create a custom SQL command, by defining attribute, predicate and value, which then translates into WHERE Statement you already mentioned. I don't see any possibility to tell Ransack directly to filter for what you want. However:

What you could is create a scope like:

scope :column_b_gt_columnb_a, -> { where('column_b > column_a') }

And then you can build your search like this:

Object({ column_b_gt_columnb_a: true })

Probably not really what you were looking, but I think that's the best you gonna get...

And if you want to do it with Rails you would do to compare values or use said where statement I used above.

Records.each do |i|
case i.variable_a
  when i.variable_b
    # do something when it's the same
  when i.variable_a > i.variable_b
    # do something when it's greater
  end
end

For an example of an SQL statement look here

How do I compare two columns for equality in SQL Server?

Hope this helps a bit!

like image 126
Thomas Avatar answered Nov 09 '22 05:11

Thomas