# Easy way

**URL:** <https://www.ruby-forum.com/t/easy-way/154125>\
**Category:** Rails\
**Created:** [November 25, 2008, 5:10pm UTC](https://www.ruby-forum.com/t/easy-way/154125 "2008-11-25T17:10:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [November 25, 2008, 5:10pm UTC](https://www.ruby-forum.com/t/easy-way/154125/1 "2008-11-25T17:10:12Z")

</div>

Best way to do this:

Pseudo code

(word is unique)

1 Select \* from words where word = “test”  
2 If result \> 0 then update words set count = coun +1  
3 else Insert into words (word, count) values (“test”, 1)

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [November 25, 2008, 5:11pm UTC](https://www.ruby-forum.com/t/easy-way/154125/2 "2008-11-25T17:11:44Z")

</div>

Sorry

> 2 If result \> 0 then update words set count = coun + 1 where word = “test”

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [November 25, 2008, 6:19pm UTC](https://www.ruby-forum.com/t/easy-way/154125/3 "2008-11-25T18:19:16Z")

</div>

On Tue, Nov 25, 2008 at 5:10 PM, Gi Ga  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Best way to do this:
> 
> Pseudo code
> 
> (word is unique)
> 
> 1 Select \* from words where word = “test”  
> 2 If result \> 0 then update words set count = coun +1  
> 3 else Insert into words (word, count) values (“test”, 1)

class Word \< ActiveRecord::Base  
end

word = Word.find\_or\_create\_by\_name(“test”)  
word.count = word.count + 1  
word.save

will propably do the job

–  
Gabriel L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
