Jquery 在Rails中使用空关联过滤AJAX数据表
我正在使用Jquery 在Rails中使用空关联过滤AJAX数据表,jquery,ruby-on-rails,ruby,ajax,datatable,Jquery,Ruby On Rails,Ruby,Ajax,Datatable,我正在使用ajaxdatatables railsgem生成一个服务器端处理的数据表。我的datatable类如下所示: class StoreDatatable < AjaxDatatablesRails::Base def view_columns @view_columns ||= { id: {source: "Store.id"}, name: {source: "Store.name"}, item_qty: {source:
ajaxdatatables rails
gem生成一个服务器端处理的数据表。我的datatable类如下所示:
class StoreDatatable < AjaxDatatablesRails::Base
def view_columns
@view_columns ||= {
id: {source: "Store.id"},
name: {source: "Store.name"},
item_qty: {source: "Item.qty"},
item_name: {source: "Item.name"},
}
end
def data
records.map do |record| {
id: record.id,
name: record.name,
item_qty: record.item.try(:qty),
item_name: record.item.try(:name),
}
end
end
private
def get_raw_records
Store.includes(:item).all
end
end
class Store < ApplicationRecord
has_one :item
end
class Item < ApplicationRecord
belongs_to: store
end
def index
respond_to do |format|
format.html
format.json { render json: StoreDatatable.new(view_context) }
end
end
$('#store').dataTable
processing: true
serverSide: true
searching: true
lengthMenu: [10, 25, 50, 100]
ajax: $('#store').data('source')
columns: [
{data: 'id'}
{data: 'name'}
{data: 'item_qty',
defaultContent: ""},
{data: 'item_name',
defaultContent: ""},
]
deferRender: true
数据表的咖啡脚本如下所示:
class StoreDatatable < AjaxDatatablesRails::Base
def view_columns
@view_columns ||= {
id: {source: "Store.id"},
name: {source: "Store.name"},
item_qty: {source: "Item.qty"},
item_name: {source: "Item.name"},
}
end
def data
records.map do |record| {
id: record.id,
name: record.name,
item_qty: record.item.try(:qty),
item_name: record.item.try(:name),
}
end
end
private
def get_raw_records
Store.includes(:item).all
end
end
class Store < ApplicationRecord
has_one :item
end
class Item < ApplicationRecord
belongs_to: store
end
def index
respond_to do |format|
format.html
format.json { render json: StoreDatatable.new(view_context) }
end
end
$('#store').dataTable
processing: true
serverSide: true
searching: true
lengthMenu: [10, 25, 50, 100]
ajax: $('#store').data('source')
columns: [
{data: 'id'}
{data: 'name'}
{data: 'item_qty',
defaultContent: ""},
{data: 'item_name',
defaultContent: ""},
]
deferRender: true
我可以很好地显示表,但当我尝试筛选表的结果时,由于空关联,我会得到错误。并非所有的存储
都必须有项
,但我需要能够显示所有存储
,无论它们是否有项
(这就是为什么我在获取原始记录
方法中使用包含
而不是连接
)
尝试筛选结果时,我在Rails中遇到的错误是:
ActiveRecord::StatementInvalid(Mysql2::错误:“where子句”中的未知列“item.qty”
如何让datatable的筛选器处理空关联?关联需要可搜索
我正在使用Rails 5.1.2、Ruby 2.4.1和最新的Datatables发行版(包括gem)。根据使用时的说明,其中条件包含包括:
像这样使用where
只有在传递哈希时才起作用。对于SQL片段,需要使用引用
强制联接表
因此,您可能需要向
get_raw_records`添加references(:item)来完成这项工作。我从未使用过这个gem,但是如果您向get_raw_records
添加references(:item)
会发生什么情况?“对于SQL片段,您需要使用引用来强制连接表”(谢谢!这似乎已经做到了。