在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
我可以做些什么来使这种关联在两个方面都得到实现?
答案 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