Skip to content

Unable to order by computed field defined as method in model, only fields as in database columns are working. #392

Open
@sameer1612

Description

@sameer1612

Taking same city example:

How to proceed if I want to sort by "full_name"?

City model :

`
class City < ApplicationRecord
belongs_to :country

def full_name
name + ' city'
end
end
`

city_datatable.rb :

`
def view_columns
@view_columns ||= {
check_box: { source: 'City.id', orderable: false, searchable: false },
name: { source: 'City.name' },
iata: { source: 'City.iata' },
country_name: { source: 'City.country_id', cond: filter_country_condition },
full_name: { source: 'City.full_name', searchable: false }
}
end

def data
records.map do |record|
{
check_box: record.decorate.to_checkbox(selected: selected.include?(record.id)),
name: record.name,
iata: record.iata,
country_name: record.country.try(:name),
full_name: record.full_name
}
end
end
`

Haml file changes.

`

  • t.head_for_check_box
  • t.head_for :name, label: City.human_attribute_name('name')
  • t.head_for :iata, label: City.human_attribute_name('iata')
  • t.head_for :country_name, label: City.human_attribute_name('country_name')
  • t.head_for :full_name, label: City.human_attribute_name('full_name')
    `

ERROR :

`
Completed 500 Internal Server Error in 9ms (ActiveRecord: 1.0ms | Allocations: 2457)

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: cities.full_name):

app/datatables/city_datatable.rb:15:in map' app/datatables/city_datatable.rb:15:in data'
app/controllers/cities_controller.rb:15:in block (2 levels) in datatable' app/controllers/cities_controller.rb:14:in datatable'
`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions