如何从数组中删除活动记录对象

时间:2022-09-25 07:44:45

I have set of active record object in array.

我在数组中设置了活动记录对象。

I just want to delete on object from array not in database

我只想删除数组中的对象而不是数据库中的对象

a = Model.limit(2)

b = Model.first

a.delete(b)

returning nil value

返回零值

Its not deleting

它没有删除

is there anyway?

还有吗?

3 个解决方案

#1


23  

a.to_a - [b]

Background: a.to_a convertrs the relation into an array in in memory.
[b] is an array whith just the element, you want to delete (in memory).
a.to_a - [b] does an array substraction.

背景:a.to_a将关系转换为内存中的数组。 [b]是一个只有元素的数组,你要删除(在内存中)。 a.to_a - [b]做一个数组减法。

(In Rails 3.2 .to_a was applied automatically to a relation when it was accessed. I agree with gregates: It's better to convert the relation to an array explicitly)

(在Rails 3.2中.to_a在被访问时自动应用于关系。我同意gregates:最好将关系明确地转换为数组)

#2


14  

There's potentially some confusion here because in ActiveRecord, Model.limit(2) does not return an array.

这里可能存在一些混淆,因为在ActiveRecord中,Model.limit(2)不返回数组。

Model.limit(2).class #=> ActiveRecordRelation

So when you call a.delete(b), you may not be calling Array#delete.

所以当你调用a.delete(b)时,你可能不会调用Array#delete。

Try this instead:

试试这个:

a = Model.limit(2).to_a # Executes the query and returns an array
b = Model.first
a.delete(b)

#3


1  

This is what you need:

这就是你需要的:

objects_in_db = Model.all
objects_in_array = Model.first(2)
objects_in_array.delete_if { |obj| !objects_in_db.include?(obj)}

In your case, Model.limit(2) may not return the first two object and so the array a may not contain b and hence, it returns nil.

在您的情况下,Model.limit(2)可能不会返回前两个对象,因此数组a可能不包含b,因此它返回nil。

#1


23  

a.to_a - [b]

Background: a.to_a convertrs the relation into an array in in memory.
[b] is an array whith just the element, you want to delete (in memory).
a.to_a - [b] does an array substraction.

背景:a.to_a将关系转换为内存中的数组。 [b]是一个只有元素的数组,你要删除(在内存中)。 a.to_a - [b]做一个数组减法。

(In Rails 3.2 .to_a was applied automatically to a relation when it was accessed. I agree with gregates: It's better to convert the relation to an array explicitly)

(在Rails 3.2中.to_a在被访问时自动应用于关系。我同意gregates:最好将关系明确地转换为数组)

#2


14  

There's potentially some confusion here because in ActiveRecord, Model.limit(2) does not return an array.

这里可能存在一些混淆,因为在ActiveRecord中,Model.limit(2)不返回数组。

Model.limit(2).class #=> ActiveRecordRelation

So when you call a.delete(b), you may not be calling Array#delete.

所以当你调用a.delete(b)时,你可能不会调用Array#delete。

Try this instead:

试试这个:

a = Model.limit(2).to_a # Executes the query and returns an array
b = Model.first
a.delete(b)

#3


1  

This is what you need:

这就是你需要的:

objects_in_db = Model.all
objects_in_array = Model.first(2)
objects_in_array.delete_if { |obj| !objects_in_db.include?(obj)}

In your case, Model.limit(2) may not return the first two object and so the array a may not contain b and hence, it returns nil.

在您的情况下,Model.limit(2)可能不会返回前两个对象,因此数组a可能不包含b,因此它返回nil。