用户#index中的ActiveRecord :: StatementInvalid? HABTM。

时间:2015-10-09 21:51:55

标签: ruby-on-rails

我脚手架的文章和用户。当我尝试检索用户索引上的文章名称时,我收到此错误消息。我认为这表示连接表并不存在。如何解决这个问题?

错误读取:

   ActiveRecord::StatementInvalid in Users#index

    PG::UndefinedTable: ERROR:  relation "articles_users" does not  
       exist
    LINE 5:                WHERE a.attrelid =   
          '"articles_users"'::regcla...
                                      ^

   :               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                 pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
            FROM pg_attribute a LEFT JOIN pg_attrdef d
              ON a.attrelid = d.adrelid AND a.attnum = d.adnum
           WHERE a.attrelid = '"articles_users"'::regclass
             AND a.attnum > 0 AND NOT a.attisdropped
           ORDER BY a.attnum

用户表

  class CreateUsers < ActiveRecord::Migration
   def change
    create_table :users do |t|
     t.string :name
     t.timestamps null: false
    end
   end
  end

文章表:

    class CreateArticles < ActiveRecord::Migration
     def change
      create_table :articles do |t|
       t.string :article_name
       t.timestamps null: false
      end
     end
    end

加入表:

   class CreateArticlesUsersJoin < ActiveRecord::Migration
    def change
     create_table :articles_users_joins do |t|
       t.belongs_to :article, index: true
       t.belongs_to :user, index: true
      end
     end
    end

文章协会:

   class Article < ActiveRecord::Base
       has_and_belongs_to_many :users
   end

用户关联:

   class User < ActiveRecord::Base
      has_and_belongs_to_many :articles
   end

1 个答案:

答案 0 :(得分:0)

HABTM默认使用两个模型名称作为连接表

在您的情况下,HABTM默认使用“articles_users”作为连接表

如果要将另一个表用作连接表,只需使用“:join_table”选项

class Article < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => "articles_users_joins"
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :articles, :join_table => "articles_users_joins"
end

source