我有两个由has_many / belongs_to实现的具有多对多关系的模型,如下所示:
this.route
.queryParamMap
.map(params => params.get('coordinates'))
.subscribe(coordinates => this.navigationService.navigateTo(coordinates))
这些表是在以下迁移中创建的:
class Author < ApplicationRecord
has_many :author_books
has_many :books, :through => :author_books, :validate => false
end
class Book < ApplicationRecord
has_many :author_books
has_many :authors, :through => :author_books, :validate => false
end
class AuthorBook < ApplicationRecord
belongs_to :author
belongs_to :book
end
当我执行以下测试代码时:
create_table :books do |t|
t.string :name
t.integer :price
end
create_table :authors do |t|
t.string :name
end
create_table :author_books do |t|
t.integer :book_id
t.integer :author_id
t.integer :percent
end
我得到以下好的结果:
Book.delete_all
Author.delete_all
AuthorBook.delete_all
author1 = Author.create name: 'a1'
author2 = Author.create name: 'a2'
book = Book.new name: 'b', price: 40
book.authors = Author.where("id = #{author1.id} or id = #{author2.id}")
ret = book.save
AuthorBook.all.each do |ab|
puts "Author id #{ab.id} author #{ab.author_id} book #{ab.book_id}"
end
但是当我将以下Author id 1 author 980190963 book 980190963
Author id 2 author 980190964 book 980190963
添加到AuthorBook:
after_save
我得到以下好的结果:
after_save :f
def f
self.book.author_books.each do |ab|
# nothing
end
end
事实上,当我检查数据库时,我可以看到AuthorBook记录在其book_id字段中包含nil。知道为什么会这样吗?