我似乎在rails 4应用程序中将我的关联错误连接起来。这基本上是我的设置(虽然有点做作)
型号:
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
当我想检查在rails控制台中正确设置的模型时,我会执行以下操作:
u = User.first
u.books => NameError: uninitialized constant User::BooksAndUser
我做错了什么?
答案 0 :(得分:0)
将book_and_user.rb
重命名为books_and_user.rb