ActiveRecord调用方法合并

时间:2014-04-25 11:55:56

标签: ruby-on-rails postgresql activerecord ruby-on-rails-4 rails-activerecord

我需要从coalesce调用方法Rails。怎么做?

categories = Entity.joins(:language, :category).
        select("coalesce('entities.short_descr', 'categories.short_descr')").
        where('languages.code = ?', 'en')

    render json: {status: 'ok', categories: categories}

不起作用,返回

{"status":"ok","categories":[{"coalesce":"entities.short_descr","id":null}]}

2 个答案:

答案 0 :(得分:1)

您可以使用Arel构建查询

categories = Entity.joins(:language, :category)
  .select(
    Arel::Nodes::NamedFunction.new(
      'coalesce', 
      Entity.arel_table[:short_descr], 
      Category.arel_table[:short_descr]
    )
  )
  .where(
    Language.arel_table[:code].eq('en')
  )

答案 1 :(得分:0)

select('categories.*, coalesce(entities.short_descr, categories.short_descr) as short_descr,
            coalesce(entities.full_descr, categories.full_descr) as full_descr')