【问题标题】:Access HABTM join table records访问 HABTM 连接表记录
【发布时间】:2015-04-25 04:39:44
【问题描述】:

我的应用程序中有这样的 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 和 Author 的记录:

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

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

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

是否可以更改连接表行?

【问题讨论】:

  • 你不能。 has_and_belongs_to_many 使用连接 table,而不是连接 model。您想将has_many :through 与连接模型一起使用。

标签: ruby-on-rails ruby-on-rails-4 join many-to-many rails-console


【解决方案1】:

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

希望有用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多