删除使用关联关联的记录时,如何解决无效语句has_and_belongs_to



我有一个连接表,我没有使用传统的Rails约定来命名。它连接ParticipantGroup模型(使用 has_and_belongs_to 关联),通常命名为 groups_participants

我尝试销毁Group模型中的记录,并收到无效语句错误"找不到表'groups_participants'"

我的连接表没有命名为groups_participants,而是命名为"matchups"

这是问题所在吗?是否需要更改连接表名称?通过阅读几篇文章,为联接表提供别名是可以接受的。

这是我从 schema.rb 的连接表

     create_table "matchups", id: false, force: :cascade do |t|
t.integer "group_id",       null: false
t.integer "participant_id", null: false
t.index ["group_id", "participant_id"], name: "index_matchups_on_group_id_and_participant_id"
t.index ["participant_id", "group_id"], name: "index_matchups_on_participant_id_and_group_id"
   end

这是我的错误页面中突出显示的代码:

    def table_structure(table_name)
      structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA')
      raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
      table_structure_with_collation(table_name, structure)
    end

尝试删除我的Group模型中存在的记录,由于找不到" groups_participants"而无法这样做。

由于您的联接表不遵循 Rails 命名约定,因此请确保通过在has_and_belongs_to_many关联上指定 join_table 选项来告诉 Rails 正确的名称是什么:

has_and_belongs_to_many :participants, join_table: :matchups

最新更新