AJAX DataTables Rails-查询不适用于显示器



让我们从数据库模型开始:

# => ProductSelection.rb
has_many :products, -> { uniq }, through: :product_variants
# => Product.rb
has_many :product_informations
belongs_to :product_configuration
belongs_to :product_class

在轨道上使用普通红宝石,我们收集了products以显示product_selection#show -Method中的显示:

@products = ProductSelection.find(params[:id]).products.includes(:product_informations, :product_class, :product_configuration)

并生成了这样的表:

  = table(@products).as(:products).default do |product|
    = product.name
    = product.product_configuration.name
    = product.product_class.name
    = product.state
    = link_to product_product_selection_path(@product_selection, product_id: product.id), method: :delete

现在我们要使用DataTables而不是轨道上的普通红宝石。

我们正在使用Ajax-Datables-rails-gem。我们希望所有列最终都可以分类和搜索。不幸的是,我们没有经过查询来检索属于ProductSelectionProducts

这是我们到目前为止尝试的查询:

 def get_raw_records
    ProductSelection.find(params[:id]).products.includes(:product_informations, :product_class, :product_configuration).references(:product_information, :product_class, :product_configuration).distinct
 end

 def data
    records.map do |record|
      [
        record.name,
        record.product_configuration.name,
        record.product_class.name,
        record.state,
        record.id
      ]
    end
  end

弹出的错误:

> undefined method `each_with_index' for nil:NilClass

在添加可排序/可搜索的列时,错误是以下内容:

PG::UndefinedColumn at /product_selections/fetch_table_data_show.json
=====================================================================
> ERROR:  column products.name does not exist
LINE 1: SELECT  DISTINCT "products"."id", products.name

具有这样的配置:

  def sortable_columns
    # Declare strings in this format: ModelName.column_name
    @sortable_columns ||= %w(Product.name ProductConfiguration.name ProductClass.name Product.state)
  end
  def searchable_columns
    # Declare strings in this format: ModelName.column_name
    @searchable_columns ||= %w(Product.name ProductConfiguration.name ProductClass.name Product.state)
  end

我认为问题在于这里的不同模型。我假设DataTables-rails期望ProductSelection的型号,但使用Product提示。任何帮助将不胜感激!如果有任何东西,请告诉我!

在另一个查看之后,我们发现问题是Product.name不是有效的ActivereCord-Construct。相反,它是在道路上某个地方定义的辅助方法。

由于宝石试图通过列标记查找记录,因此发生了此错误。

我们通过删除相关列来解决它。其他方法将是:

  1. 将数据存储在单独的列中,而不是使用助手。
  2. 在JavaScript中实现助手行为,以便我们可以通过 它是对DataTables的回调。