0

我是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 

我怎麼能這樣做呢?

回答

1

在模型authors_book,你應該這樣做

class AuthorsBook < ActiveRecord::Base 
    belongs_to :author 
    belongs_to :book 
end 

在authors_books表中的每個條目AUTHOR_ID和保持這種多對多的assosiation books_id。 現在,當你做了這個

@author.books 

將取回所有這些是筆者寫的書。

您可以輕鬆遍歷這些書籍並顯示它們。

+0

檢查此railscast的多對多關係。這是非常有幫助的。 http://railscasts.com/episodes/47-two-many-to-many – Athar

+0

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association – Athar

+0

非常感謝!我只需要這樣的東西! – mike927

1

我認爲你應該修改一下代碼。還有,我知道要實現兩個方法很多-to-many關聯:

  1. has_and_belongs_to_many
  2. 的has_many通過

如果你想使用中間連接表 'authors_books',你應該使用has_and_belongs_to_many,但在這種情況下,您無法按模型訪問authors_books表,因爲沒有關於它的模型。

如果你想存儲一些數據或信息到intermedidate連接表,你應該建立由導軌產生CMD模型像$ rails g model AuthorBook somedata:integer,並使用has_many through。最後,刪除'authors_books'表。代碼如下:

class Author < ActiveRecord::Base 
    has_many :authorbooks 
    has_many :books, through: :authorbooks 
end 

class Book < ActiveRecord::Base 
    has_many :authorbooks 
    has_many :authors, through: :authorbooks 
end 

class Authorbook < ActiveRecord::Base 
    belongs_to :books 
    belongs_to :authors 
end 
0
Many-to-Many association in rails can be achieve through, 
has_many:_______ ; through:______ 

Ex: Physicians has many patients through appointments.Also, physicians has many appointments. 
    Patients has many physicians through appointments. Also, here patients has many appointments. 
Here the common entity is appointments. So DHH, has implemented many-to-many like this way. 

physicians 
    has_many :appointments 
    has_many :patients, through: :appointments 
patients 
    has_many :appointments 
    has_many :physicians, through: :appointments 
appointments 
    belongs_to :physicians 
    belongs_to :patients  

希望這將有助於。

+0

是的,這是有幫助的! – mike927