访问HABTM连接表的记录
问题描述:
我有一个像这样在我的应用程序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
中的记录?
是可以改变连接表的行吗?
答
如果要访问连接表记录,则必须使用has-many-through
关系重新创建连接表。这里有一个很好的指导,以及has-many-through
和has-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
一旦他们”重新添加。
希望有用!
你不能。 'has_and_belongs_to_many'使用join _table_,而不是join _model_。你想在连接模型中使用'has_many:through'。 – Substantial 2015-02-23 18:46:23