Rails控制台混乱

Bit*_*ise 3 ruby console ruby-on-rails

我想删除更多只有一个id.我正在使用Person.find(1).destroy.

有没有办法可以选择多于一个数据记录?

tod*_*eny 5

是.您可以在控制台中编写脚本.

Person.find_each do |person|
  if # condition for deleting
    person.destroy
  end
end
Run Code Online (Sandbox Code Playgroud)

或者,如果您知道所有ID ...您可以使用where子句然后销毁所有这些.

ids = [1,2,3,4,5]

people = Person.where(id: ids) # where can take an array of ids
people.each { |person| person.destroy }
Run Code Online (Sandbox Code Playgroud)

  • 你也可以调用`Person.where(id:[1,2,3]).destroy_all`和`delete_all`(参见http://stackoverflow.com/questions/6698207/delete-all-vs-destroy-all更多信息) (5认同)