Delete only from non-database memory

I have an ActiveRecord array containing a list of stores.

shops = Shop.find(:all)

I want to delete an entry from stores without deleting it from the database.

shops.delete(a_shop)will delete the SQL query. I just want the store to be removed from the ActiveRecord array, but not the database.

Can this be done?

thanks

+3
source share
4 answers

Beware if you use has_many relationships, JP response will not work.

Extension example:

class City < ActiveRecord::Base
  has_many :shops
end

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

then

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

Remove from the database!

Besides

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

Will remove from the database

One way to disconnect from the database is to use a compact or other array function, for example:

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

, delete_if db:

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

!

: script/console - !

+9

, delete . .

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

:

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

. ? , Rails 2.1.

-JP

+5

, .

, . - :

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

, . , , .

+1

I would suggest such a way to delete an AR object in memory.
Add the attribute to the appropriate model, which is responsible for marking the AR object as remote (for example, deleted):

class OrderItem <ActiveRecord :: Base ... attr_accessor: deleted

 def deleted
   @deleted || 'no'
 end

end

Mark the corresponding object as deleted:

o.order_items {|oi| oi.deleted = 'yes' if oi.id == 1029}

The order_items filter specifies only not deleted rows:

o.order_items do |oi| 
 unless oi.deleted == 'yes'
 ...
 end
end
0
source

Source: https://habr.com/ru/post/1704512/


All Articles