如何将Arel查询与ActiveRecord方法链接?

时间:2019-03-17 08:02:03

标签: ruby-on-rails activerecord arel

我正在发现Arel,并且对如何返回到RoR 5.2应用程序中默认使用的ActiveRecord对象有些困惑。

最初,我的业务规则索引数据集定义为:

@business_rules = BusinessRule.pgnd(current_playground_scope). 
search(params[:criteria]).order("hierarchy ASC").
paginate(page: params[:page], :per_page => paginate_lines)

现在,转换表提供了“名称”和“描述”列,这使查询更加复杂。那就是Arel进来的地方:

names = Translation.arel_table.alias('tr_names')
descriptions = Translation.arel_table.alias('tr_descriptions')
rules = BusinessRule.arel_table
translated_rules = rules.
join(names, Arel::Nodes::OuterJoin).on(rules[:id].eq(names[:document_id]).and(names[:language].eq(user_language).and(names[:field_name].eq('name')))).
join(descriptions, Arel::Nodes::OuterJoin).on(rules[:id].eq(descriptions[:document_id]).and(descriptions[:language].eq(user_language).and(descriptions[:field_name].eq('description'))))

rules_extract = translated_rules.project(Arel.star)
sql = rules_extract.to_sql
@rules_index = ActiveRecord::Base.connection.execute(sql)

#suggestions for better organising Arel's tree are welcome

to_sql方法提供了令人满意的SQL查询,但是execute方法的结果返回了一个PG :: Result类,在该类中我期望有ActiveRecord_Relation。

仔细阅读后,我发现了很多有关Arel功能的信息,但是我仍然错过了在索引视图中重新使用Arel的链接。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

实际上,Arel将查询块提供给标准ActiveRecord查询接口。这使我可以重写原始的Rails索引查询,并添加两次别名链接表:

def index
  names = Translation.arel_table.alias('tr_names')
  descriptions = Translation.arel_table.alias('tr_descriptions')
  rules = BusinessRule.arel_table
  translated_rules = rules.
    join(names, Arel::Nodes::OuterJoin).on(rules[:id].eq(names[:document_id]).and(names[:language].eq(user_language).and(names[:field_name].eq('name')))).
    join(descriptions, Arel::Nodes::OuterJoin).on(rules[:id].eq(descriptions[:document_id]).and(descriptions[:language].eq(user_language).and(descriptions[:field_name].eq('description')))).
    join_sources

  @business_rules = BusinessRule.joins(translated_rules).order("hierarchy ASC, major_version, minor_version").paginate(page: params[:page], :per_page => paginate_lines)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @business_rules }
  end
end

现在,我可以对查询进行智能重构了,并可以从Translations表中检索翻译的字段了!