Active Record 提供了 :inverse_of 选项,可以通过它明确声明双向关联:
class Author < ApplicationRecord has_many :books, inverse_of: 'writer'
end
class Book < ApplicationRecord belongs_to :writer, class_name: 'Author', foreign_key: 'author_id'
end
在 has_many 声明中指定 :inverse_of 选项后,Active Record 便能识别双向关联:
a = Author.first b = a.books.first a.first_name == b.writer.first_name # => true a.first_name = 'David' a.first_name == b.writer.first_name # => true