2016-11-04 87 views
0

我试图根据jquery-bootgrid制作一个可重用的库。在可链接的activerecord函数中链接Activerecord函数

当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()会隐藏那些标准的/ limit/offset/order选项,并返回一个为视图准备好的关系。理想情况下,它也为视图填充@object_count,然后添加限制/偏移量/订单详细信息 - 一个jquery-bootgrid的东西。

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

这应该实现为lib /中的某些东西吗?作为ActiveSupport ::关注?

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

回答

1

我觉得一个的ActiveSupport ::关注

至于如何建立/控制器实例填充@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。

+0

必须在controller.instance_variable_set之前和之后放置部件才能获得正确的预期编号,但似乎工作正常。谢谢。 – user6167808

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)