2

I have a column called school_id in a table called records.

Now I have an array of school_ids and I want to delete all the records that has the following ids that belong to the array.

The question is, is there a way to do it with just one line of command? Like:

Record.delete_all(:school_id => [1, 2, 3, 4])?

Right now I'm doing a looping here and as much as possible I'm trying to simplify that part. TIA

6 Answers 6

2

You can use your way. I hope you are using Rails 3.x

Record.delete_all(:school_id => [1, 2, 3, 4])

It generates SQL

DELETE FROM "records" WHERE "records"."school_id" IN (1, 2, 3, 4)
Sign up to request clarification or add additional context in comments.

1 Comment

actually I forgot to mention that it is in Rails 2.x
1

check this out destroy_all

It expects a string, array, or hash of ids to delete.

I often add another action to the controller for destroy_multiple

def destroy_multiple
  current_user.entries.destroy_all(:id => params[:user_ids])
  redirect_to entries_url
end

don't forget to add the collection route..

Comments

0

I don't know too much about rails, but you can do it pretty easily in SQL:

delete from records where school_id in (1,2,3,4)

Hope that helps?

Comments

0
School.where('id IN (?)', school_ids).destroy_all

Comments

0
Record.where(:school_id => [1, 2, 3, 4]).delete_all

Comments

0

It's simple

Record.where(school_id: school_ids).delete_all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.