I'm using ajax-datatables-rails
and want to use an associated model in the datatable file, I want to use the include()
method. However, it's not that simple. According to https://github.com/jbox-web/ajax-datatables-rails, their include()
example is extremely complicated and goes far beyond what I'm trying to do.
I have a model called Page
and one called Book
for example, and I just simply want to use Pages.include(:book)
so that I can call page.book
in my view later on.
How can I accomplish that using their scenario? Here's what I tried, but it didn't work:
# app/datatables/example_datatable.rb
# Allow the use of helpers in JSON response.
def_delegators :@view, :link_to, :book_path
def view_columns
# Declare strings in this format: ModelName.column_name
# or in aliased_join_table.column_name format
@view_columns ||= {
# id: { source: "User.id", cond: :eq},
# name: { source: "User.name"}
position: { source: "Page.position"},
book_name: { source: "Page.book.book_name"},
}
end
def data
records.map do |record|
{
# example:
# id: record.id,
# name: record.name
position: record.position,
book_name: link_to("#{record.book.book_name}", book_path(record), remote: true),
}
end
end
private
def get_raw_records
# insert query here
Page.includes(:book).references(:book).distinct
end
If I just left it at Pages.includes(:book)
then I get an error in my datatable only when I attempt to use the search/filter textbox. Otherwise, things are displayed just fine.
The error that I get states:
Unknown column 'pages.book' in 'where clause'
In their example, they stated that references(:related_model)
is in here, but I'm not exactly sure how to swing it using my simple one-model-association.
According to the ajax-datatables-rails README it looks like you might need to:
Book.name
into your @view_columns
instead of Page.book.name
joins(:book)
instead of include/references