1

我有一個像這樣在我的應用程序HABTM關係:訪問HABTM連接表的記錄

class Book < ActiveRecord::Base 
    has_and_belongs_to_many :authors 
end 

class Author < ActiveRecord::Base 
    has_and_belongs_to_many :books 
end 

在軌控制檯我可以訪問圖書的記錄,作者是這樣的:

Book.all 
Book.first 
b = Book.first 
b.title = "Title2" 
b.save 
... 

但我不知道如何訪問連接表。

如何訪問並查看連接表books_authors中的記錄?

是可以改變連接表的行嗎?

+0

你不能。 'has_and_belongs_to_many'使用join _table_,而不是join _model_。你想在連接模型中使用'has_many:through'。 – Substantial 2015-02-23 18:46:23

回答

4

如果要訪問連接表記錄,則必須使用has-many-through關係重新創建連接表。這裏有一個很好的指導,以及has-many-throughhas-and-belongs-to-many之間的區別,在這裏:http://railscasts.com/episodes/47-two-many-to-many

你需要創建一個類似以下內容來創建連接表一個新的遷移:

class Authorships < ActiveRecord::Migration 
    def change 
    create_table :authorships do |t| 
     t.belongs_to :book, index: true 
     t.belongs_to :author, index: true 

     t.timestamps null: false 
    end 
    add_foreign_key :authorships, :books 
    add_foreign_key :authorships, :authors 
    end 
end 

其中「的著者」可以是任何名稱您認爲適合的連接表(或「BookAuthors」如果你會想堅持)。

作爲一個簡單的例子,你的模型可能看起來像以下:

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

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

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

您可以添加額外的列到連接表並訪問他們根據需要,與authorship_ids一起,和Author.first.books/Book.first.authors一旦他們」重新添加。

希望有用!