Nei*_*eil 4 activerecord ruby-on-rails
现在我的方法是一次列出每个表并调用.delete_all它.这是重复的:
例:
#app/db/seeds.rb
Blog.delete_all
Person.delete_all
Post.delete_all
User.delete_all
Author.delete_all
Book.delete_all
# ... on and on for all the tables
Run Code Online (Sandbox Code Playgroud)
然后当然运行rake db:seed将清除上表中的所有记录.
是否有一个命令完全符合我的要求:
或者,有没有办法迭代我的所有表和.delete_all每个表?
是否有一个命令完全符合我的要求:删除所有表中的所有记录?
bundle exec rake db:reset
Run Code Online (Sandbox Code Playgroud)
这在功能上等同于rake db:drop db:setup.
不想删除表吗?
#app/db/seeds.rb
[Blog, Person, Post, User, Author, Book].each do |table|
ActiveRecord::Base.connection.execute("TRUNCATE #{table.table_name}")
end
Run Code Online (Sandbox Code Playgroud)
由于OP要求删除所有表中的所有记录,而不是所有表.因此,您可以通过以下方式获取所有表:ActiveRecord::Base.connection.tables它将为您提供数据库中的所有表.
puts ActiveRecord::Base.connection.tables
ActiveRecord::Base.connection.tables.each do |table|
next if table.match(/\Aschema_migrations\Z/)
klass = table.singularize.camelize.constantize
klass.delete_all
end
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你想id重新开始1,当你create清空表后的新实例时,你必须destroy在表中重新创建它.
ActiveRecord::Migration.drop_table(:users)
ActiveRecord::Migration.create_table(:users)
Run Code Online (Sandbox Code Playgroud)
现在,如果您创建一个新的模型实例User,它将id从中开始生成1.请注意,您需要发送表的名称drop_table和create_table函数,而在上面我写的代码为您提供了类的名称,在这种情况下User.如果您拥有模型的名称,则可以获取表名称:
User.table_name # it will give you "users"
# in above code, you can do:
ActiveRecord::Migration.drop_table(klass.table_name)
# string and symbol: both type of arguments work here!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3305 次 |
| 最近记录: |