2016-11-04 7 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オプションの標準を隠し、ビューの準備ができた関係を返します。理想的には、limit/offset/orderの詳細(jquery-bootgridのもの)を追加する前に、ビューの@object_countも設定します。

http://craftingruby.com/posts/2015/06/29/query-objects-through-scopes.htmlは面白そうに見えましたが、模型に靴ひもの模型をしようとすると(少なくともレール3.2.8で)一見不可能です。

これはlib /に何かとして実装する必要がありますか? ActiveSupport :: Concernとして?

最初に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) 
関連する問題