jbox-web / ajax-datatables-rails

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
MIT License
590 stars 227 forks source link

Q: NoMethodError when trying to get data from 3 models in has_many / belongs_to association #253

Closed matissg closed 7 years ago

matissg commented 7 years ago

I'm trying to implement has_many / belongs_to association and at the moment I'm a bit stuck as I can't populate data from 3 models.

My models look like this:

class Medium::Medium < ApplicationRecord
  has_many :inventories, class_name: 'Inventory::Inventory', through: :positions, source: :inventories
  has_many :positions, -> { includes :inventories }, dependent: :destroy, class_name: 'Position::Position', inverse_of: :medium
end

class Position::Position < ApplicationRecord
  belongs_to :medium, optional: true, class_name: 'Medium::Medium', inverse_of: :positions
  has_many :inventories, dependent: :destroy, class_name: 'Inventory::Inventory', inverse_of: :position
end

class Inventory::Inventory < ApplicationRecord
  belongs_to :position, class_name: 'Position::Position', optional: true, inverse_of: :inventories
end

then in my Datatables I have this:

class MyDatatable < AjaxDatatablesRails::Base

  def view_columns
    @view_columns ||= {
      medium: { source: "Medium::Medium.name", cond: :like },
      position:  { source: "Position::Position.name", cond: :like },
      date: { source: "Inventory::Inventory.date", cond: :like },
    }
  end

  private

  def data
    records.map do |record|
      {
        medium: record.name,
        position: record.name,
        date: record.date,
      }
    end
  end

  def medium
    @medium ||= options[:medium]
  end

  def get_raw_records
    Medium::Medium.where(id: medium).includes(positions: :inventories)
                                    .references(:position, :inventory)
  end

end

and my JS looks like this:

jQuery(document).ready(function() {
  $('#mytable').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": $('#outdoor-table').data('source'),
    "pagingType": "full_numbers",
    "columns": [
      {"data": "medium"},
      {"data": "position"},
      {"data": "date"},
    ]
  });
});

In my terminal I can see there is one big query loading all data for all 3 models and then I have this error: NoMethodError (undefined method "date" for #<Medium::Medium:0x007f27b9b97a48> As I understand my def data method is getting data from Medium::Medium model only. How do I fix this to get data from all 3 models as needed, please? So far I've tried to do as described in associated and nested models section.