让我们从数据库模型开始:
# => 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
. 任何帮助将不胜感激!如果有什么遗漏,请告诉我!