我正在使用ajax-datatables-rails
gem來生成服務器端處理過的數據表。我的DataTable類看起來是這樣的:在Rails中使用空關聯過濾AJAX Datatables
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
我可以很好地顯示錶格,但是當我嘗試過濾表格結果時,由於空關聯而出現錯誤。不是所有的Stores
必然有Items
,但我需要能夠顯示所有Stores
,無論他們是否有Items
(這就是爲什麼我在get_raw_records
方法中使用includes
而不是joins
)。
我Rails中得到,當我嘗試過濾結果的錯誤是:
ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'item.qty' in 'where clause'
怎樣纔可以有DataTable中的過濾器,空協會合作?這些協會需要被搜索。
我正在使用最新的Datatables版本(包括gem)的Rails 5.1.2,Ruby 2.4.1。
我從來沒有使用過這個gem,但是如果給''get_raw_records'添加'references(:item)'會發生什麼? 「對於需要使用強制連接表的引用的SQL片段」([來自指南](http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations)) –
謝謝!這似乎已經成功了。 – Wes