I have a model

```
class Log < ActiveRecord::Base
  attr_accessible :key, :value
end

```

Given this Log table:

```
id: 1, key: "apple", value: "tasty", 
id: 2, key: "apple", value: "green",  
id: 3, key: "apple", value: "sour",  
id: 4, key: "orange", value: "juicy",  
id: 5, key: "orange", value: "round",  
id: 6, key: "banana", value: "yellow",      

```

I want a **scope** that returns the last log for each unique key, namely logs with id `3, 5, 6` affirming that apples are sour, oranges are round and bananas - yellow.

I would like to do this on the database side, but lacking knowledge I can only imagine a ruby-side solution with an inefficient loop

```
Log.all.pluck(:key).uniq.map {|key| Log.where(key: key).last }

```

Needless to say, looping over all unique keys would grow slow as table content increases and, most importantly, would return an array, not ActiveRecord::Relation object.

Can this even be done with SQL?