2014-12-28 74 views
-1

我似乎在我的rails 4應用程序中連線錯誤。這基本上是我的設置(雖然有點做作)NameError:未初始化的常量User :: BooksAndUser在has_many:通過關聯

型號:

book.rb

class Book < ActiveRecord::Base 
    has_many :books_and_users 
    has_many :users, through: :books_and_users 
    validates :user_id, presence: true 
end 

user.rb

class User < ActiveRecord::Base 
    has_many :books_and_users 
    has_many :books, through: :books_and_users 
    validates :name, presence: true 
end 

book_and_user .rb

class BooksAndUser < ActiveRecord::Base 
    self.table_name = "books_and_users" 
    belongs_to :book 
    belongs_to :user 
    validates :user, presence: true 
    validates :book, presence: true 
end 

模式

create_table "books", force: true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "user_id" 
end 

add_index "books", ["user_id"], name: "index_books_on_user_id" 

create_table "books_and_users", force: true do |t| 
    t.integer "user_id" 
    t.integer "book_id" 
end 

add_index "books_and_users", ["book_id"], name: "index_books_and_users_on_book_id" 
add_index "books_and_users", ["user_id"], name: "index_books_and_users_on_user_id" 

create_table "users", force: true do |t| 
    t.string "email",     default: "", null: false 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "name" 
end 

當我要檢查的模型是建立在正確的軌道控制檯我做了以下內容:

u = User.first 
u.books => NameError: uninitialized constant User::BooksAndUser 

我在做什麼錯?

+0

嘗試改變'User'和'Book'了'books_and_users'協會指定的類名像這樣:'的has_many:books_and_users,CLASS_NAME: 「BooksAndUser」'我想你' 'BooksAndUser'中的table_name'規範可能是必要的。嘗試刪除該行。附:您忘記分享您的「Book」模型的代碼 - 您在帖子中分享了兩次「BookAndUser」模型。 – Humza

+0

@Humza我做了所有這些,但仍然得到相同的錯誤。 :-( – patriques

+0

錯誤是否告訴你哪一行出錯? – Humza

回答

0

重命名book_and_user.rbbooks_and_user.rb

相關問題