0

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

# => ProductSelection.rb
has_many :products, -> { uniq }, through: :product_variants

# => Product.rb
has_many :product_informations
belongs_to :product_configuration
belongs_to :product_class

使用普通的 Ruby on Rails,我们收集了- 方法中的products显示,product_selection#show如下所示:

@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 而不是普通的 Ruby on Rails。

我们正在使用Ajax-Datatables-Rails-Gem。我们希望所有列最终都是可排序和可搜索的。不幸的是,我们没有通过查询来检索问题的Products归属ProductSelection

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

 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. 任何帮助将不胜感激!如果有什么遗漏,请告诉我!

4

1 回答 1

0

再看一遍后,我们发现问题在于它Product.name不是有效的 ActiveRecord 构造。相反,它是在某个地方定义的辅助方法。

由于 gem 尝试通过列名查找记录,因此发生了此错误。

我们通过删除有问题的列来解决它。其他方法是:

  1. 将数据存储在单独的列中,而不是使用帮助程序。
  2. 在 javascript 中实现助手行为,以便我们可以将其作为回调传递给数据表。
于 2016-12-02T11:44:11.007 回答