has_and_belongs_to_many的奇怪错误PG :: UndefinedColumn:错误:列articles.article_id

时间:2016-11-21 10:47:49

标签: ruby-on-rails ruby-on-rails-4

我已经定义了两个模型,它们都用has_and_belongs_to_many相互引用

class Category < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

class Article < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

我添加了一个迁移:

class CreateJoinTableArticleCategory < ActiveRecord::Migration
  def change
    create_join_table :articles, :categories do |t|
      t.index [:article_id, :category_id]
      t.index [:category_id, :article_id]
    end
  end
end

尝试编辑rails admin http://localhost:3000/admin/article/20/edit

中的文章时,我遇到了这个奇怪的错误
    Showing /Users/me/.rvm/gems/ruby-2.2.2/gems/rails_admin-0.7.0/app/views/rails_admin/main/_form_filtering_multiselect.html.haml where line #10 raised:

    PG::UndefinedColumn: ERROR:  column articles.article_id does not exist

1 个答案:

答案 0 :(得分:0)

试试这个

class CreateJoinTableArticleCategory < ActiveRecord::Migration
  def change
    create_join_table :articles, :categories do |t|
      t.index :article_id
      t.index :category_id
    end
  end
end

参考:api doc

修改:无需在连接表中添加索引和主键。

参考:see this answer