我最近偶然发现了belongs_to
和has_many
添加的一些方法的奇怪行为。
考虑以下情况,如Rail's Active Record Association guide所示。
class Author < ApplicationRecord
has_many :books, inverse_of: :author
end
class Book < ApplicationRecord
belongs_to :author, inverse_of: :books
end
如果我使用belongs_to
&#39; association=(associate)
method,我会忽略作者对该书的提及:
book = Book.new
author = Author.new
book.author = author
author.books.include?(book) # false, expected true
author.books.empty? # true, expected to contain book
但如果我与has_many
collection<<(object)
method建立关联,则该参考会按预期持续存在:
book = Book.new
author = Author.new
author.books << book
author.books.include?(book) # true, as expected
author.books.empty? # false, as expected
book.author == author # true, as expected
这是预期的行为吗?我不太明白为什么第一个案例不存储从author
到book
的关联。
我使用ruby 2.5.1和rails 5.2.0。
提前致谢。
答案 0 :(得分:0)
author.books << book
构建ActiveRecord::Associations::CollectionProxy
。因此,使用author.books.include? book
检查它是否存在于该集合中(尚未存储在db中):它是真的。
只需book.save
即可保存book
和author
。
相反,book.author = author
只是一项任务。您需要author.save
和book.save
才能有效地建立关系。如果你在两次保存后检查author.books.include?(book),如果变为true。
在rails控制台中试用。