我是Rails的新手,遇到問題。我有三個表格:書籍,作者,書籍作者。在我看來,我想顯示兩列。首先應該顯示作者的名字,以及作者寫下十進制的所有書籍。在我的books_authors表中,外鍵屬於書籍和作者表中的主鍵。我的架構:Rails Many_to_many association
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
我怎麼能這樣做呢?
檢查此railscast的多對多關係。這是非常有幫助的。 http://railscasts.com/episodes/47-two-many-to-many – Athar
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association – Athar
非常感謝!我只需要這樣的東西! – mike927