How to write this better? Ruby Sequel chaining OR
Asked Answered
G

2

9

In SQL it should look like this:

SELECT * FROM `categories_description_old` WHERE ((`categories_description` = '') OR (`categories_name` = '') OR (`categories_heading_title` = ''))

My (ugly) solution:

conditions = [:categories_name, :categories_heading_title, :categories_description]
b = table_categories_description_old.filter(conditions.pop => "")
conditions.each do |m|
 b = b.or(m => "")
end

Is there a better solution to chain the or conditions?

Giblets answered 15/11, 2010 at 15:28 Comment(0)
S
3

You can do something like:

conditions.inject(table_categories_description_old.filter(true)){|acc, cond|
  acc.or(cond => '')
}

But in cases like this when you have already thought out SQL query, I find it easier to just type whole WHERE condition and use Sequel just to sanitize my query parameters.

Sophistication answered 15/11, 2010 at 16:6 Comment(1)
it should be filter(false) instead, otherwise conditions are not checkedSpill
T
17
 DB[:categories_description_old].
   filter({:categories_description=>'',
           :categories_name=>'',
           :categories_heading_title=>''}.sql_or)
Telencephalon answered 15/11, 2010 at 18:21 Comment(0)
S
3

You can do something like:

conditions.inject(table_categories_description_old.filter(true)){|acc, cond|
  acc.or(cond => '')
}

But in cases like this when you have already thought out SQL query, I find it easier to just type whole WHERE condition and use Sequel just to sanitize my query parameters.

Sophistication answered 15/11, 2010 at 16:6 Comment(1)
it should be filter(false) instead, otherwise conditions are not checkedSpill

© 2022 - 2024 — McMap. All rights reserved.