Overriding new_record?

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

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.

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs