【问题标题】:How to truncate a join table in rails?如何截断rails中的连接表?
【发布时间】:2010-09-09 02:30:14
【问题描述】:

要截断 ActiveRecord 表,我可以这样做

Category.destroy_all

Post.destroy_all

如何截断categories_post 表?

【问题讨论】:

    标签: ruby-on-rails activerecord truncate


    【解决方案1】:

    对于真正的TRUNCATE,您可以使用execute 运行原始SQL。

    ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name}")
    

    您使用模型的示例没有执行真正的TRUNCATE 查询。

    • destroy_all 不是TRUNCATE 一个表。它“通过实例化每条记录并调用其销毁方法来销毁符合条件的记录”(link)。
    • delete_all 更接近 - 它忽略回调 - 但仍然不是 TRUNCATE

    使用execute 方法从数据库中删除行而不创建任何模型实例。

    另外,至少在 MySQL 中,实际的 TRUNCATE 查询将重置主键的自动增量,以便您插入的下一条记录的 id 为 1。

    【讨论】:

    • ActiveRecord::Base.connection.execute("TRUNCATE TABLE table_name")
    【解决方案2】:

    我猜你的连接表叫做 categories_posts。 CategoryPost.destroy_all 应该可以,如果不行,可能需要在模型中指定表名(CategoryPost)

    set_table_name "categories_posts"
    

    更新,没有 CategoryPost 模型,所以应该创建它:

    class CategoryPost < ActiveRecord::Base
      set_table_name "categories_posts"
    end 
    

    【讨论】:

    • 连接表没有关联的模型。例如,CategoryPost
    猜你喜欢
    • 2020-07-14
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2018-02-27
    • 2017-03-21
    相关资源
    最近更新 更多