Ruby-on-rails 如何从数组中删除活动记录对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16883709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:06:09  来源:igfitidea点击:

how to remove active record object from array

ruby-on-railsruby

提问by sangeethkumar

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?

有吗?

回答by Martin M

a.to_a - [b]

Background: a.to_aconvertrs 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:最好将关系显式转换为数组)

回答by gregates

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

有可能一些混乱,因为这里在ActiveRecordModel.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)

回答by itz2k13

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 amay not contain band hence, it returns nil.

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