views:

146

answers:

3

Hi all,

I have an ActiveRecord array containing a list of shops.

shops = Shop.find(:all)

I want to delete a record from shops without deleteting it from the database.

shops.delete(a_shop) wuold result in a delete sql querry. I just want the shop to be deleted from the activerecord array but not the database.

Can this be done?

Thanks

+2  A: 

I don't think you can remove the item from the array.

However, you should be able to modify your find to return the array without that shop initially. Something like:

shops = Shop.find(:all, :conditions => "id NOT #{a_shop.id}")

should be along the lines of what you want. That way you never get the shop in the container in the first place, but it doesn't affect the database.

workmad3
This will work once, but if more than one shop needs to be removed, you'll have to do something else.And you can remove items from the array.
Tilendor
+5  A: 

When I did some testing, calling the delete method does not actually delete the element from the database. Only from the array.

shops = Shop.find(:all)
shops.delete(shops[0]) #deletes the first item from the array, not from the DB

To delete from the DB:

shops = Shop.find(:all)
Shop.delete(shops[0].id)

See the distinction? At least, this how it works on my Rails 2.1 setup.

-JP

JP
+2  A: 

Beware if you are using has_many relationship the answer by JP will not work.

Extending the example:

class City < ActiveRecord::Base
  has_many :shops
end

city = City.find(:name => "Portland")

then

city.shops.delete(city.shops[0])

Will delete from the DB!

Also

theshops = city.shops
theshops.delete(ss[0])

Will delete from the DB

One way to detach from the DB is to use compact or another array function like so:

theshops = city.shops.compact
theshops.delete(ss[0])

Will not delete from the DB

Also, in all cases delete_if Will not delete from the db:

city.shops.delete_if {|s| s.id == city.shops[0]}

Cheers!

Don't forget: If you are in doubt about these sort of things script/console is your friend!

bpaul