Remove element from ActiveRecord_Relation in rails

Very late too, but I arrived here looking for a fast answer and finished by thinking by myself ;)

Just to clarify about the different answers and the Rails 6.1 comment on accepted answer:

The OP wanted to remove one entry from a query, but NOT remove it from database, so any answer with delete or destroy is just wrong (this WILL delete data from your database !!).

In Ruby (and therefore Rails) convention, shebang methods (ending with !) tend to alter the given parameter. So reject! would imply modifying the source list ... but an ActiveRecord_Relation is basically just a query, NOT an array of entries !


So you'd have 2 options:

  • Write your query differently to specifically say you don't want some id:
@drivers.where.not(id: @driver_to_remove)  # This still is an ActiveRecord_Relation
  • Use reject (NO shebang) on your query to transform it into an Array and "manually" remove the entry you don't want:
@drivers.reject{ |driver| driver ==  @driver_to_remove}
# The `reject` forces the execution of the query in DB and returns an Array)

On a performance point of view, I would personally recommend the first solution as it would be just a little more complex against the DB where the latter implies looping on the whole (eventually large) array.


You can use the reject! method, this will remove the object from the collection without affecting the db

for example:

driver_to_delete = @driver.first # you need the object that you want removed
@drivers.reject!{|driver| driver == driver_to_delete}

Late to the question, but just had the same issue and hope this helps someone else.

reject!did not work for ActiveRecord_Relation in Rails 4.2

drop(1) was the solution

In this case @drivers.drop(0) would work to drop the first element of the relation