2

I got 2 models. One called Header and another one called Alarm

Alarm has a column called keyword. Header have 4 columns called title_en, title_es, title_eu, title_fr

I would like to compare these 4 columns of a given Header against the keyword field for every single Alarm. This should extract the Alarms which match somehow any of the titles.

The query I have built(see below) works in a weird way. I have tried with some fake data:

Alarm1.keyword = 'foo'
Header1.title_es = 'foo'
Header2.title_en = 'foo'
Header3.title_en = 'foo'

This query returns Alarm1 only with Header2 and Header3. Why does not work for Header1? Anything to do with title_es.

@header = Header.find(somegivenheader)
@alarms =  Alarm.where((["CAST(alarms.keyword as varchar(255)) LIKE ?", @header.title_en] || ["CAST(alarms.keyword as varchar(255)) LIKE ?", @header.title_es] || ["CAST(alarms.keyword as varchar(255)) LIKE ?", @header.title_fr] || ["CAST(alarms.keyword as varchar(255)) LIKE ?", @header.title_eu]))

Any help much appreciated. Thanks

4

1 回答 1

1

I don't think those where clauses are being ORed together as you expect. Take a look at the resulting SQL in the console by appending .to_sql to Alarm.where(...).

Or, try something like:

Alarm.where("keyword in (?)", [@header.title_es, @header.title_fr, @header.title_eu])
于 2013-04-16T14:41:00.480 回答