Question

I want to query my psql database from my rails app using the example query string:

select * from venues where upper(regexp_replace(postcode, ' ',  '')) = '#{postcode}' or name = '#{name}'

There are 2 aspects to this query:

  • the first is to compare against a manipulated value in the database (upper and regexp_replace) which I can do within an active record where method
  • the second is to provide the or condition which appears to require the use of ARel

I would appreciate some help in joining these together.

Was it helpful?

Solution

See squeel, it can handle OR queries and functions in a pretty human friendly way: https://github.com/activerecord-hackery/squeel & http://railscasts.com/episodes/354-squeel

for example:

[6] pry(main)> Page.where{(upper(regexp_replace(postcode, ' ', '')) == 'foo') | (name == 'bar')}.to_sql
=> "SELECT \"pages\".* FROM \"pages\"  WHERE upper(regexp_replace(\"pages\".\"postcode\", ' ', '')) = 'foo'"

alternative is to code the query directly:

scope :funny_postcode_raw, lambda{ |postcode, name| where("upper(regexp_replace(postcode, ' ',  '')) = ? or name = ?", postcode, name) }

I don't suggest going the Arel path, not worth it 99.9% of the time

NOTE: the OR operator for squeel is |

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top