使用ActiveRecord和Postgres进行异或连接条件查询

时间:2015-01-13 11:56:34

标签: ruby-on-rails postgresql activerecord arel

我有两张桌子。

create_table "categories", force: true do |t|
  t.string   "title"
  t.string   "slug"
  t.boolean  "is_public",  default: false
  t.integer  "row_order"
end

create_table "localizations", force: true do |t|
  t.string   "lang"
  t.string   "title"
  t.text     "content"
  t.integer  "category_id"
end

我需要执行一个查询,该查询会为每个属性返回一些不同的类别属性以及相应的localizations.title。条件是连接的本地化是两个传递的lang值之一,其中第一个值优先。

我的第一次尝试是:

Category.
  select(:id, :slug, :row_order).
  select('localizations.title AS localized_title').
  distinct.
  joins(:localizations).
  where(localizations.lang = :first OR localizations.lang = :last, first: 'en', last: 'pl')

然而,它没有按预期完全发挥作用,因为如果有lang = 'en'的翻译,而另一个lang = 'pl'的翻译,则返回它们,因为它们被视为不同的记录。据我所知,XOR中没有postgres运算符。

我的第二次尝试是在where子句中创建一个条件,该条件首先使用lang = 'en'查询本地化,如果这样的本地化不存在 - lang = 'pl'

Category.
  select(:id, :slug, :row_order).
  select('localizations.title AS localized_title').
  distinct.
  joins(:localizations).
  where('localizations.lang = CASE WHEN EXISTS(SELECT localizations.id FROM localizations WHERE localizations.lang = :first) THEN :first ELSE :last', first: 'en', last: 'pl')

不幸的是,由于某种原因,它会抛出语法错误。

0 个答案:

没有答案