Rails has_many和belongs_to具有意外行为的关联方法

时间:2018-06-06 16:02:51

标签: ruby-on-rails ruby associations has-many belongs-to

我最近偶然发现了belongs_tohas_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

这是预期的行为吗?我不太明白为什么第一个案例不存储从authorbook的关联。

我使用ruby 2.5.1和rails 5.2.0。

提前致谢。

1 个答案:

答案 0 :(得分:0)

author.books << book构建ActiveRecord::Associations::CollectionProxy。因此,使用author.books.include? book检查它是否存在于该集合中(尚未存储在db中):它是真的。

只需book.save即可保存bookauthor

相反,book.author = author只是一项任务。您需要author.savebook.save才能有效地建立关系。如果你在两次保存后检查author.books.include?(book),如果变为true。

在rails控制台中试用。