如何在Ruby on Rails 5.2中优化和干燥范围?

问题描述

为了使我的应用程序干燥,我在application_record.rb文件中定义了“可见”范围(所有表都存在):

scope :visible,-> { where "is_active" }

当我查询对象列表时,如果需要确定数据范围,则将以下int编写为控制器:

def index
@values_lists = ValuesList.joins(requested_values_lists).visible.search(params[:criteria]).
  select(index_fields).order(order_by).paginate(page: params[:page],:per_page => paginate_lines)

实际上,此values_lists表链接到users表(定义所有者)和business_areas表(定义父表)。为了优化查询,我尝试使用Arel在同一查询中检索values_list,父级和所有者:

def values_lists
  ValuesList.arel_table
end

def values_lists_parent
  BusinessArea.arel_table.alias('parent')
end

def values_lists_owner
  User.arel_table.alias('owner')
end

def requested_values_lists
  values_lists.
  join(values_lists_parent).on(values_lists[:business_area_id].eq(values_lists_parent[:id])).
  join(values_lists_owner).on(values_lists[:owner_id].eq(values_lists_owner[:id])).
  join_sources
end

def index_fields
  [values_lists[:id],values_lists[:code],values_lists[:name],values_lists[:description],values_lists[:status_id],values_lists[:updated_by],values_lists[:updated_at],values_lists_parent[:code],values_lists_owner[:name]]
end

在没有范围的情况下,查询工作正常,但是在应用范围时,我收到一条消息,指出“模糊列名is_active”。有办法解决这个问题吗?

非常感谢!

解决方法

我通过让 Rails 做聪明的工作解决了这个问题:

application_record.rb

scope :visible,-> { where is_active: true }

自己解析表名!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...