rubyruby-object-mapper

Ruby Object Mapper - How to change the default order field in a Create command?


I am current working on a project that I want to use Ruby Object Mapper with an existing sql database. I am running into a problem when I execute a create command, the returned result seems to sort by table_name.id by default. This is a problem because the existing tables that I am working with has a primary key named other than id, and it causes a unknown column 'id' exception.

I just wonder if there is any possible way to change the default order column?


Solution

  • Just got answer from Github:

    This is an issue related with rom-sql (https://github.com/rom-rb/rom-sql/blob/master/lib/rom/sql/relation.rb#L39).

    The solution is to declare your dataset explicitly in the relation of your command. Try something like this:

    class MyRelation < ROM::Relation[:sql]
      dataset { order(:my_column) }
    end
    

    https://github.com/rom-rb/rom/issues/339#issuecomment-193904733

    Update:

    Alternatively you can also set that in the container definition using :macros:

    rom_container = ROM.container(:sql, 'mysql2://root@localhost/db_name') do |rom|
      rom.use :macros
    
      rom.relation(:users) do |r|
        r.primary_key :my_column
        r.dataset { order(:my_column) }
      end
    end