【问题标题】:Custom Responder for jqGrid data in railsrails 中 jqGrid 数据的自定义响应程序
【发布时间】:2012-01-30 22:53:18
【问题描述】:

我认为这很容易。定义一个“to_grid”响应模块,将其包含在适当的地方使用,让 jqgrid 使用“/client.grid”之类的 url 进行交互,并能够与 html 响应者共享休息动作。我查看了一系列 jqGrid gem,但没有看到任何在最近添加的代码、兼容 rails 3.1、gem 而非插件和完全 REST 访问的最佳位置。

但显然我对响应者的理解不够深入,或者这是一个完全不合适的策略选择。

jqGrid 是一个基于 JQuery 的数据网格,它使用 JSON 与服务器进行通信。我的策略是这样的......

#Gemfile
gem 'kaminari'
gem 'responder'
gem 'inherited_resources'

#config/initializers/mime_types.rb
Mime::Type.register "application/json", :grid

#lib/application_responder.rb
require 'grid_responder'
class ApplicationResponder < ActionController::Responder
  include Responders::GridResponder
end

#lib/grid_responder.rb
module Responders
  module GridResponder
    extend ActiveSupport::Concern
    module InstanceMethods
      def to_grid
        #Only pagination included at this time.
        if get? && resource.is_a?(ActiveRecord::Relation)
          total = resource.klass.count
          page, rows = controller.params[:page], controller.params[:rows]
          paginated = resource.page(page).per(rows)
          output = { total: (total / rows) + 1,
                     page: page,
                     records: total,
                     rows: resource }
          render json: output.to_json
        end
      end
    end
  end
end

#app/controllers/application_controller.rb
require "application_responder"
class ApplicationController < ActionController::Base
  self.responder = ApplicationResponder
  respond_to :html, :json, :grid
end

#app/controllers/client_controller.rb
class ClientController < InheritedResources::Base
end

但是调用 /client.grid 是因为找不到模板。我真的没想到需要一个模板。我开始怀疑这种策略是否值得追求。我有大约十几个模型需要网格化,而且在 12 个不同的控制器中做同样的事情似乎不是很干。

问题:这种策略是否值得采用,或者是否有更容易或更惯用的策略。

额外问题:一个指向工作的 Rest/Responder 代码的指针,我可以阅读并用作模型。

谢谢!

【问题讨论】:

  • 您写了这个问题,因此需要了解 Ruby on Rails 才能理解您的问题。另一方面,您的主要问题是关于与 jqGrid 的通信。只有生成的 JSON 输入的格式对 jqGrid 很重要。如果需要,您可以添加 HTTP 标头(如果 RESTfull 服务器也是您的问题的一部分)。如果您要添加一个 JSON 示例来生成您的 Ruby on Rails 程序,那么更多的人可以理解您想要做什么,并且可能会给您一些有用的建议。
  • jqGrid 是我的 rails 应用程序输出的使用者。但是,我的问题是在 Rails 方面,jqGrid 仅作为示例提及。我删除了 jqGrid 标签。我了解 json 输出的外观,我可以在 rails 上生成它以供 jqGrid 使用。我遇到的问题是了解如何扩展 ActionController::Responder 以便我可以自动生成 json 并使用模块代码,因此我遵循 DRY 原则。现在,对于我想提供给 jqGrid 的每个资源,我都需要编写特定于该资源的代码。

标签: ruby-on-rails ruby-on-rails-3.1


【解决方案1】:

这里有很多潜在的问题:

我认为这意味着您的条件返回 false 并且未调用渲染,因此它正在寻找默认情况下要渲染的视图模板。您是否检查以确保 resource.is_a?(ActiveRecord::Relation) 为您的用例返回 true? Inherited Resources 不会为资源返回 ActiveRecord::Relation - 它应该返回一个 ActiveRecord::Base 实例。

另外,如果你不需要,你的自动加载路径中是否有 lib

require Rails.root.join("lib/application_responder")

另外,您能否确认 to_grid 方法正在被调用?

我建议使用 pry:https://github.com/pry/pry 来反省这里发生的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多