# Create or update\_attribute method

**URL:** <https://www.ruby-forum.com/t/create-or-update-attribute-method/170748>\
**Category:** Rails\
**Created:** [June 22, 2009, 12:06pm UTC](https://www.ruby-forum.com/t/create-or-update-attribute-method/170748 "2009-06-22T12:06:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![on9west](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6f9a4e/32.png) [@on9west](https://www.ruby-forum.com/u/on9west)\
**Post date:** [June 22, 2009, 12:06pm UTC](https://www.ruby-forum.com/t/create-or-update-attribute-method/170748/1 "2009-06-22T12:06:07Z")

</div>

Dear all

Are there any method to create or update something? (if something exist,  
then update, else create…where something is the primary key)

Something like…  
if Klass.find\_by\_something( xxx )  
Klass.update\_attribute your\_hash  
else  
Klass.create your\_hash  
end

This is similar to the AR dynamic finder  
Klass.find\_or\_create\_by\_something()…, but I want a  
Klass.create\_or\_update\_by\_something…Any idea??

Many thanks  
Valentino

---

<div class="post-metadata">

**Author:** ![on9west](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6f9a4e/32.png) [@on9west](https://www.ruby-forum.com/u/on9west)\
**Post date:** [June 22, 2009, 2:10pm UTC](https://www.ruby-forum.com/t/create-or-update-attribute-method/170748/2 "2009-06-22T14:10:36Z")

</div>

On Mon, Jun 22, 2009 at 12:06 PM, Valentino  
Lun[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Klass.create your\_hash  
> end
> 
> This is similar to the AR dynamic finder  
> Klass.find\_or\_create\_by\_something()…, but I want a  
> Klass.create\_or\_update\_by\_something…Any idea??
> 
> Many thanks  
> Valentino

I don’t think so, how about:  
Klass.send(“find\_or\_create\_by\_#{attributes.map{|k,v|  
k}.join(“_and_”)}”, \*attributes.map{|k,v| v})  
WARNING: This is a quick solution and could break because I’m relying  
on the fact that the hash will return in the same order for both calls

Andrew T.  
[http://ramblingsonrails.com](http://ramblingsonrails.com)

[http://MyMvelope.com](http://MyMvelope.com) - The SIMPLE way to manage your savings
