【问题标题】:Rails has_many and belongs_to association methods with unexpected behaviour具有意外行为的 Rails has_many 和 belongs_to 关联方法
【发布时间】:2018-06-06 16:02:51
【问题描述】:

我最近在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_toassociation=(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_manycollection&lt;&lt;(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。

提前致谢。

【问题讨论】:

  • 检查 bookauthor。因为你有new,而不是create,所以也没有id。因此,无法使用book.author = author 正确设置关联(在book 上没有author.id 可以设置为author_id)。
  • @jvillian 我明白这一点,但我希望关联存储在内存中,就像(我认为)使用 collection&lt;&lt;(object) 而不是 association=(associate) 时所做的那样。
  • book.author_id 上没有设置外键时,我不知道您所说的“存储在内存中”是什么意思。但是,您可以查看源代码,我相信一切都会清楚。顺便说一句,我怀疑如果您查看控制台,您可能还会发现一些启发性信息。

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


【解决方案1】:

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

只需book.save,您就可以同时保存bookauthor

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

在 Rails 控制台中尝试一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多