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

时间:2015-09-16 17:26:45

标签: 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 = 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

我可以做些什么来使这种关联在两个方面都得到实现?

1 个答案:

答案 0 :(得分:2)

您需要指定inverse_of

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