Mar*_*rio 1 many-to-many join ruby-on-rails rails-console ruby-on-rails-4
我的应用程序中有一个 HABTM 关系,如下所示:
class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
end
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
end
Run Code Online (Sandbox Code Playgroud)
在 Rails 控制台中,我可以像这样访问 Book 和 Author 的记录:
Book.all
Book.first
b = Book.first
b.title = "Title2"
b.save
...
Run Code Online (Sandbox Code Playgroud)
但我不知道如何访问连接表。
如何访问和查看连接表中的记录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
Run Code Online (Sandbox Code Playgroud)
其中“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
Run Code Online (Sandbox Code Playgroud)
您可以将额外的列添加到连接表并根据需要访问它们,以及添加后的authorship_ids, 和Author.first.books/ Book.first.authors。
希望有用!
| 归档时间: |
|
| 查看次数: |
1035 次 |
| 最近记录: |