Rails 4.1.9 通过关联重命名 table 错误

Rails 4.1.9 renaming table error on through associations

好吧,我有三个表用户,组,groups_users 我 运行 迁移以将 groups_users 重命名为 memberships

rename_table :groups_users, :memberships

一切正常,但这个关联

has_and_belongs_to_many :groups, through: memberships, class: "Group"

抛出以下错误:

PG::UndefinedTable: ERROR:  relation "groups_users" does not exist

我在我的整个项目中搜索了一个关于旧名称的被遗忘的参考,但没有找到。有什么想法吗?

has_and_belongs_to_many 协会没有 through 选项,您应该使用 join_table 选项。

has_and_belongs_to_many :groups, join_table: 'memberships'

来自 rails 个礼物:https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).

You should use has_many :through if you need validations, callbacks or extra attributes on the join model.

我猜你的 Memership 模型比连接模型有更多的功能,所以你应该使用 has_many :through 关联。