简体   繁体   English

如何删除并返回ActiveRecord关系对象中的第一个元素?

[英]How can I remove and return the first element in an ActiveRecord relation object?

I want to remove and return the first element in an AR relation object. 我想删除并返回AR关系对象中的第一个元素。 I used shift , but it does not remove the object. 我使用了shift ,但它没有移除对象。

With a normal array, shift works as expected: 使用普通数组,shift按预期工作:

a = [1, 2, 3]
a.shift # => 1
a # => [2, 3]

This does not work. 这不起作用。 The variable @attachment_versions retains the same size before and after using shift . 变量@attachment_versions在使用shift之前和之后保持相同的大小。

@attachment = Attachment.with_associations.find(params[:id])
@attachment_versions = @attachment.attachment_versions
@current_version = @attachment_versions.shift

# this raises `true`
raise @attachment_versions.include?(@current_version).to_s

def self.with_associations
  includes(attachment_versions: :owner, comments: [:author, :attachments])
end

I know that an AR relation object is more than just an Array, but I thought shift should work in the same way. 我知道AR关系对象不仅仅是一个数组,但我认为shift应该以相同的方式工作。

You can pretty easily turn it into an array first. 你可以很容易地把它变成一个数组。

ie

@attachment_versions_array = @attachment_versions.to_a

@attachment_versions_array.shift
=> <Attachment_version......etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM