ajax-datatables-rails icon indicating copy to clipboard operation
ajax-datatables-rails copied to clipboard

Problem in searching in table with association

Open DJ621 opened this issue 6 years ago • 2 comments

Hi guys , I have a problem while searching in the table if i use association . I have pasted the codes below .

Audit logs Model :

class AuditLog < ApplicationRecord
  belongs_to :user
end

User Model :

class User < ApplicationRecord
  has_many :audit_logs, foreign_key: 'user_id'

AuditLogDatatable :

class AuditLogDatatable < AjaxDatatablesRails::ActiveRecord
  extend Forwardable
  def_delegator :@view, :content_tag


  def initialize(params, opts = {})
    @view = opts[:view_context]
    super
  end

  def view_columns
    # Declare strings in this format: ModelName.column_name
    # or in aliased_join_table.column_name format
    @view_columns ||= {
      id:                     { source: "AuditLog.id" },
      user_id:                { source: "AuditLog.user_id", cond: :like, searchable: true, orderable: true },
      is_admin_user:             { source: "AuditLog.is_admin_user", cond: :like, searchable: true, orderable: true },
      description:            { source: "AuditLog.description", cond: :like, searchable: true, orderable: true },
      profile_name:         { source: "AuditLog.profile_name", cond: :like, searchable: true, orderable: true },
      date:                { source: "AuditLog.date", cond: :like, searchable: true, orderable: true },
      profile_id:   { source: "AuditLog.profile_id", cond: :like, searchable: true, orderable: true },
      created_at:             { source: "AuditLog.created_at", cond: :like, searchable: true, orderable: true }
    }
  end

  def data
    records.each_with_index.map do |record, idx|
      {
        id: params[:start].to_i + idx + 1,
        user_id: record.user.first_name,
        is_admin_user: record.is_admin_user,
        description: content_tag(:span, record.description),
        profile_name: record.profile_name,
        date: record.date,
        profile_id: record.profile_id,
        created_at: record.created_at
      }
    end
  end

  def get_raw_records
     AuditLog.all
  end
end

Now if I type some string on the search bar , it performs search operation only on the audit logs columns and not on users table( associated with audit logs table ) .

I have also tried the solution mentioned in https://github.com/jbox-web/ajax-datatables-rails/issues/283 , but it didn't work ....

  def get_raw_records
     AuditLog.includes(:user).references(:user)
  end

Can someone help me out here ?

DJ621 avatar Feb 13 '19 04:02 DJ621

@Dinesh621 Can you please try this :- AuditLog.eager_load(:user) or AuditLog.left_outer_joins(:user).eager_load(:user)

sonugaur avatar Feb 15 '19 07:02 sonugaur

@Dinesh621 @sonugaur Simply reporting that the eager_load(:class) worked for my similar situation. Thank you.

johnsampson avatar Sep 16 '19 19:09 johnsampson