gpt4 book ai didi

ruby-on-rails - 访问 HABTM 连接表记录

转载 作者:行者123 更新时间:2023-12-03 09:22:03 25 4
gpt4 key购买 nike

我的应用程序中有一个 HABTM 关系,如下所示:

class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
end

class Author < ActiveRecord::Base
has_and_belongs_to_many :books
end

在rails控制台中,我可以像这样访问书籍和作者的记录:

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

但我不知道如何访问连接表。

如何访问并查看连接表 books_authors 中的记录?

是否可以更改连接表行?

最佳答案

如果您想要访问连接表记录,则必须使用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

其中“Authorships”可以是您认为适合连接表的任何名称(如果您想坚持使用,则可以是“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_idsAuthor.first.books/Book.first。添加作者后

希望有用!

关于ruby-on-rails - 访问 HABTM 连接表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28680858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com