Reputation: 1621
I want to remove and return the first element in an AR relation object. I used shift, but it does not remove the object.
With a normal array, shift works as expected:
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 = 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.
Upvotes: 4
Views: 4263
Reputation: 2195
You can pretty easily turn it into an array first.
i.e.
@attachment_versions_array = @attachment_versions.to_a
@attachment_versions_array.shift
=> <Attachment_version......etc
Upvotes: 3