Ruby on rails 通过嵌套属性实例化的关联记录不会双向链接

Ruby on rails 通过嵌套属性实例化的关联记录不会双向链接,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,Rails 4.0.13中注意到的问题 class Author < ActiveRecord::Base has_one :avatar accepts_nested_attributes_for :avatar end class Avatar < ActiveRecord::Base belongs_to :author end 类作者 # >作者:阿凡达 => # >author.avatar.author =>零 如何使此关联以两种方式实例化?您需要指定的

Rails 4.0.13中注意到的问题

class Author < ActiveRecord::Base
  has_one :avatar
  accepts_nested_attributes_for :avatar
end

class Avatar < ActiveRecord::Base
  belongs_to :author
end
类作者
当实例化一对时,化身不会链接到其作者:

> author = Author.new(name: 'John', avatar_attributes: {gravatar_id: '41dd2e0c'})
=> #<Author id: nil, name: "John", created_at: nil, updated_at: nil>

> author.avatar
=> #<Avatar id: nil, author_id: nil, gravatar_id: "41dd2e0c", created_at: nil, updated_at: nil>

> author.avatar.author
=> nil
>author=author.new(名称:'John',头像属性:{gravatar_id:'41dd2e0c'})
=> #
>作者:阿凡达
=> #
>author.avatar.author
=>零

如何使此关联以两种方式实例化?

您需要指定
的逆\u

class Author < ActiveRecord::Base
  has_one :avatar, inverse_of: :author
  accepts_nested_attributes_for :avatar
end

class Avatar < ActiveRecord::Base
  belongs_to :author, inverse_of: avatar
end
类作者
您需要
保存
作者
才能看到
作者id
进入
化身
保存没有问题。这是一个简化的模型,但我的问题是,我对阿凡达模型进行了验证,该模型的逻辑取决于作者的属性,它甚至可以与多态关联一起工作!谢谢你的回答