【发布时间】:2018-06-06 16:02:51
【问题描述】:
我最近在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 的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。
提前致谢。
【问题讨论】:
-
检查
book和author。因为你有new,而不是create,所以也没有id。因此,无法使用book.author = author正确设置关联(在book上没有author.id可以设置为author_id)。 -
@jvillian 我明白这一点,但我希望关联存储在内存中,就像(我认为)使用
collection<<(object)而不是association=(associate)时所做的那样。 -
当
book.author_id上没有设置外键时,我不知道您所说的“存储在内存中”是什么意思。但是,您可以查看源代码,我相信一切都会清楚。顺便说一句,我怀疑如果您查看控制台,您可能还会发现一些启发性信息。
标签: ruby-on-rails ruby associations has-many belongs-to