You are probably looking for the delete_all ActiveRecord method. Just use without parameters and it will delete all your records
Model.delete_all
質問
I want to create a button that will clear all the data in my table. I am using Rails 4 and SQLLite3.
I populated a table using Faker with 100 people (first_name, last_name, age). The data is presented in a view. On the same view page, I want to have a button that will delete all the data in the table (but not the table itself, i.e. not drop the table).
*Bonus points if it dynamically updates the page; although, I know that might add a lot to the code.
Let me know if I need to post anything. I am pretty new to Rails, so please feel free to explain in as much detail as possible. Thank you!
As an alternative, instead of the button, just provide the method for clearing the data from the table. Thanks.
This is all the code, including the method (provided below) that I was looking for to delete the data.
class MainController < ApplicationController
def loaddata
for i in 0..100
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
age = Faker::Number.number(2)
p = Person.new(first_name: first_name, last_name: last_name, age: age)
p.save
end
head :ok
end
def index
@people = Person.all
end
def delete
@people = Person.delete_all()
head :ok
end
end
解決
You are probably looking for the delete_all ActiveRecord method. Just use without parameters and it will delete all your records
Model.delete_all