0

here is my model:

class Thing < Ohm::Model
  attribute :created_at
  index :created_at
end

I'm not able to sort the records by datetime (created_at).

Thing.all.order_by(:created_at)
NoMethodError: undefined method `each' for #<RuntimeError:0x0000010537dec0>

I know internally everything is stored as a string, and probably that is the problem. It just seems very weird there's nothing in the library or in some contrib gem to do this.

Any suggestion?

ngw
  • 1,222
  • 1
  • 14
  • 34

1 Answers1

2

Depending on what value you are using for the timestamp, sorting by created_at can be easy to do. If you use, for example, Time.now.utc.to_i, then you can sort the records like this:

Thing.all.sort_by(:created_at)

If you want to sort them in descending order, you can do this instead:

Thing.all.sort_by(:created_at, :order => "DESC")

To iterate the results, you can use each:

Thing.all.sort_by(:created_at, :order => "DESC").each do |thing|
  printf("Thing created on %s\n", Time.at(thing.created_at.to_i))
end

If you install the ohm-contrib gem, you can include Ohm::Timestamps in your model, and it will add and update the attributes created_at and updated_at:

class Thing < Ohm::Model
  include Ohm::Timestamps

  index :created_at
end

Then you can sort by created_at as in the previous examples, but in this case you don't need to pass a created_at value because it's assigned automatically each time a model is created.

soveran
  • 872
  • 6
  • 8