【发布时间】:2015-07-13 11:17:30
【问题描述】:
我是 Rails 新手,遇到了问题。我有三个表:书籍、作者、书籍作者。在我看来,我想显示两列。首先应该显示作者的名字,其次是作者写过十进制的所有书籍。在我的 books_authors 表中,外键属于 book 和 authors 表中的主键。我的架构:
ActiveRecord::Schema.define(version: 20150709110928) do
create_table "authors", force: :cascade do |t|
t.string "name"
t.string "surname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "authors_books", id: false, force: :cascade do |t|
t.integer "author_id"
t.integer "book_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "authors_books", ["author_id"], name:
"index_author_books_on_author_id"
add_index "authors_books", ["book_id"], name:
"index_author_books_on_book_id"
create_table "books", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
模型看起来像:
class Author < ActiveRecord::Base
has_many :authors_books
has_many :books, through: :authors_books
end
class Book < ActiveRecord::Base
has_many :authors_books
has_many :authors, through: :authors_books
end
我该怎么做?
【问题讨论】:
标签: ruby-on-rails foreign-keys many-to-many relational-database