# Find efficiently "greater" string in model attribute

**URL:** <https://www.ruby-forum.com/t/find-efficiently-greater-string-in-model-attribute/185941>\
**Category:** Rails\
**Created:** [March 29, 2010, 2:38pm UTC](https://www.ruby-forum.com/t/find-efficiently-greater-string-in-model-attribute/185941 "2010-03-29T14:38:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kinunt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7c8e57/32.png) [@kinunt](https://www.ruby-forum.com/u/kinunt)\
**Post date:** [March 29, 2010, 2:38pm UTC](https://www.ruby-forum.com/t/find-efficiently-greater-string-in-model-attribute/185941/1 "2010-03-29T14:38:31Z")

</div>

How can I find efficiently the model Invoice with the greater code  
(invoice attribute) when the code is a string like “1/10”, “2/10”,  
“3/10” (without quotes) and where only the number before the slash  
count? 1/10 \< 2/10 \< 3/10 \< 11/10 \< 12/10, etc…

---

<div class="post-metadata">

**Author:** ![kinunt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7c8e57/32.png) [@kinunt](https://www.ruby-forum.com/u/kinunt)\
**Post date:** [March 29, 2010, 2:48pm UTC](https://www.ruby-forum.com/t/find-efficiently-greater-string-in-model-attribute/185941/2 "2010-03-29T14:48:12Z")

</div>

Now I’m using:

def after\_initialize  
if self.new\_record? and self.codigo.blank?  
max\_codigo = FacturaEmitida.all.map{|f|  
f.codigo.split(’/’)[0].to\_i}.max  
if !max\_codigo.nil?  
self.codigo = (max\_codigo +  
1).to\_s+’/’+Date.today.strftime("%y")  
else  
self.codigo = “1/”+Date.today.strftime("%y")  
end  
end  
end

but I think it is very inefficient.

---

<div class="post-metadata">

**Author:** ![kinunt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7c8e57/32.png) [@kinunt](https://www.ruby-forum.com/u/kinunt)\
**Post date:** [March 29, 2010, 3:35pm UTC](https://www.ruby-forum.com/t/find-efficiently-greater-string-in-model-attribute/185941/3 "2010-03-29T15:35:20Z")

</div>

On 29 March 2010 13:38, Juan K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> How can I find efficiently the model Invoice with the greater code  
> (invoice attribute) when the code is a string like “1/10”, “2/10”,  
> “3/10” (without quotes) and where only the number before the slash  
> count? 1/10 \< 2/10 \< 3/10 \< 11/10 \< 12/10, etc…

If the 10 is the year then I would suggest storing the invoice number  
(1,2,3) separately from the year. Then build the full string (1/10)  
when you need it.  
You may not even need the year code if there is a created\_at field.

Colin
