# Overriding new\_record?

**URL:** <https://www.ruby-forum.com/t/overriding-new-record/84885>\
**Category:** Rails\
**Created:** [February 8, 2007, 12:33pm UTC](https://www.ruby-forum.com/t/overriding-new-record/84885 "2007-02-08T12:33:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![giantcranes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ecd19e/32.png) [@giantcranes](https://www.ruby-forum.com/u/giantcranes)\
**Post date:** [February 8, 2007, 12:33pm UTC](https://www.ruby-forum.com/t/overriding-new-record/84885/1 "2007-02-08T12:33:05Z")

</div>

Hi,

Is it possible to override or set ActiveRecord::Base.new\_record? I would  
like to be able to do something like:

c = Category.new  
c.id = 6  
c.name = “updated name”  
c.new\_record? = false  
c.save!

This would execute an UPDATE statement instead of an INSERT.

The reason for my wanting to do this as follows:

I have a SOAP web service called ‘save\_category’. It accepts a type  
called ‘ApiCategory’ which has similar attributes. I have a helper  
mapping from Category-\>ApiCategory and Category-\>ApiCategory.

I want the Api::save\_category to do an insert when there is no  
ApiCategory.id and to do an update when there is.

Any help would be much appreciated.  
GiantCranes

---

<div class="post-metadata">

**Author:** ![giantcranes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ecd19e/32.png) [@giantcranes](https://www.ruby-forum.com/u/giantcranes)\
**Post date:** [February 12, 2007, 1:12pm UTC](https://www.ruby-forum.com/t/overriding-new-record/84885/2 "2007-02-12T13:12:53Z")

</div>

Giant C. wrote:

> This would execute an UPDATE statement instead of an INSERT.
> 
> The reason for my wanting to do this as follows:
> 
> I have a SOAP web service called ‘save\_category’. It accepts a type  
> called ‘ApiCategory’ which has similar attributes. I have a helper  
> mapping from Category-\>ApiCategory and Category-\>ApiCategory.
> 
> I want the Api::save\_category to do an insert when there is no  
> ApiCategory.id and to do an update when there is.

It can be achieved with something like this:

if id = params[:id]  
Category.update(id, params[:category])  
else  
Category.create(params[:category])  
end

–  
Sava C.

---

<div class="post-metadata">

**Author:** ![giantcranes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ecd19e/32.png) [@giantcranes](https://www.ruby-forum.com/u/giantcranes)\
**Post date:** [February 8, 2007, 2:21pm UTC](https://www.ruby-forum.com/t/overriding-new-record/84885/3 "2007-02-08T14:21:23Z")

</div>

I solved (hacked?) this by adding the following method to my model:

def save\_with\_new\_record\_ignore!  
if self.id == nil  
raise “Error saving” unless self.save  
else  
raise “Error updating” unless self.update  
end  
self  
end
