简体   繁体   English

Rails has_many和belongs_to关联方法具有异常行为

[英]Rails has_many and belongs_to association methods with unexpected behaviour

I recently stumbled upon a strange behaviour with some of the methods added by belongs_to and has_many . 最近,我偶然发现了一个奇怪的行为,该行为带有一个由belongs_tohas_many添加的方法。

Consider the following scenario, as presented by Rail's Active Record Association guide . 考虑以下情况,如Rail的Active Record Association指南所述

class Author < ApplicationRecord
  has_many :books, inverse_of: :author
end

class Book < ApplicationRecord
  belongs_to :author, inverse_of: :books
end

If I use belongs_to 's association=(associate) method , I loose reference to book from author: 如果我使用belongs_toassociation=(associate) 方法 ,那么我会松散作者的参考:

book = Book.new
author = Author.new
book.author = author
author.books.include?(book) # false, expected true
author.books.empty? # true, expected to contain book

But if I make the association with has_many 's collection<<(object) method , the reference persists as expected: 但是,如果我使用has_manycollection<<(object) 方法进行关联,则该引用将按预期持久:

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

Is this the expected behaviour? 这是预期的行为吗? I don't quite understand why the first case does not store the association from author to book . 我不明白为什么第一种情况不关联的存储authorbook

I'm using ruby 2.5.1 and rails 5.2.0. 我正在使用ruby 2.5.1和rails 5.2.0。

Thanks in advance. 提前致谢。

author.books << book builds an ActiveRecord::Associations::CollectionProxy . author.books << book构建了一个ActiveRecord::Associations::CollectionProxy So with author.books.include? book 那么对于author.books.include? book author.books.include? book you are checking if it exists inside that collection (not yet stored in db): it's true. 您正在检查author.books.include? book是否存在于该馆藏中(尚未存储在db中):是的。

With just book.save you can save both book and author . 只需book.save即可保存bookauthor

Conversely, book.author = author is just an assignment. 相反, book.author = author只是一个分配。 You need to author.save and book.save to effectively build the relation. 您需要author.savebook.save有效地建立关系。 If you check author.books.include?(book) after the two save, if becomes true. 如果在两次保存之后检查author.books.include?(book),则为true。

Try it in rails console. 在rails console中尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM