bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Order using I18n #251

Closed fabriciofreitag closed 5 years ago

fabriciofreitag commented 5 years ago

I'm saving a symbol in one of my tables, then I have equivalent I18n keys to translate that symbol with the proper description in one of my columns. Is there a way that I could make that sortable given that these strings are not in a table?

Thanks

bogdan commented 5 years ago

You'd better include the code that you are using to define the column. From what I can guess you need something like this:

SYMBOLS = [
  # the list of all possible symbols
]

column(:symbol, order: :symbol_order) do |model|
  I18n.t(model.symbol, namespace: 'my_grid.symbols')
end

def symbol_order
   order("FIELD(symbol, #{sorted_symbols.map{|s| "'#{s}'"}.join(", ")})")
end

def sorted_symbols
  SYMBOLS.sort_by do |symbol|
    I18n.t(symbol, namespace: 'my_grid.symbols')
  end
end
fabriciofreitag commented 5 years ago

Thanks for the reply, I'm currently using pg, I guess I understood the goal and I could do something using CASE, thanks again.

fabriciofreitag commented 5 years ago

if it helps someone else in the future, here's a solution like the one pointed by @bogdan but for psql:

column :task_type, order: ->(scope) { order_by_translation(scope) } do |task|
  human_name_for_task(task)
end

def self.order_by_translation(scope)
  task_titles = Workflow::TaskHandling::AVAILABLE_TASK_TYPES.keys.flat_map do |type|
    ["Workflow::Tasks::#{type.to_s.camelize}" => ActiveRecord::Base.connection.quote(human_name_for_task_type(type))]
  end
  task_titles = Hash[task_titles.reduce(&:merge).sort_by(&:second)]
  order_by = ['CASE']
  task_titles.each do |task_type, title|
    order_by << "WHEN type='#{task_type}' THEN #{title}"
  end
  order_by << 'END'
  scope.order(order_by.join(' '))
end