在可链接的activerecord函数中链接Activerecord函数

时间:2016-11-04 21:51:04

标签: ruby-on-rails rails-activerecord

我正在尝试基于jquery-bootgrid创建一个可重用的库。

当jquery-bootgrid请求更多数据时 - 分页,搜索,你有什么,请求就像

http://localhost/controller/index.json?current=1&rowCount=30&searchPhrase=&_=1478278657109

我的行动目前看起来像

def index
    respond_to do |format|
        format.html
        format.json do

            #:searchPhrase => :where et al
            some_helper_function_to_format(params) 

            @ar_objects = ArObject
                .where("some_extra_filtering IS true")
                .where(params[:where])
                .limit(params[:rowCount])
                .offset(params[:offset])
                .order(params[:sort])
        end
    end
end

我更喜欢它看起来像

def index
    respond_to do |format|
        format.html
        format.json do
            @ar_objects = ArObject
                .where("some_extra_filtering IS true")
                .jquery_bootgrid_options(params)
        end
    end
end

... jquery_bootgrid_options()会隐藏那些标准where / limit / offset / order选项,并为视图返回一个准备好的关系。理想情况下,在添加限制/偏移/订单详细信息之前,它还会为视图填充@object_count - 一个jquery-bootgrid事物。

http://craftingruby.com/posts/2015/06/29/query-objects-through-scopes.html看起来很有趣,试图将鞋拔参数放入模式中(至少在轨道3.2.8中)似乎是不可能的。

这应该在lib /中实现吗?作为ActiveSupport ::关注?

如何正确链接第一个where()?

2 个答案:

答案 0 :(得分:1)

我认为ActiveSupport :: Concern

关于如何在控制器实例中创建/填充@object_count,只要传递控制器实例,就可以在调用中执行此操作

@ar_objects = ArObject.where("some_extra_filtering IS true")
                .jquery_bootgrid_options(self, params)

然后在控制器中设置实例变量...

module BootgridExtension
  extend ActiveSupport::Concern
  module ClassMethods
    def jquery_bootgrid_options(controller, params={})
      # various stuff to create query_result
      controller.instance_variable_set(:@object_count, query_result.count) 
      return query_result
    end
  end
end

这将"自动"在控制器方法中创建@object_count。

答案 1 :(得分:0)

你可以改为使用类方法。

class ArObject
  def self.jquery_bootgrid_options(params={})
    where(params[:where])
    .limit(params[:rowCount])
    .offset(params[:offset])
    .order(params[:sort])
  end
end

然后就像你一样将它链接到控制器中。

@ar_objects = ArObject
                .where("some_extra_filtering IS true")
                .jquery_bootgrid_options(params)
相关问题