Skip to content

Conversation

@rubyonme
Copy link

class User
  include Mongoid::Document
  field :name 
  has_many :posts

  accepts_nested_attributes_for :posts
end

class Post
  include Mongoid::Document
  field :title
  field :body

  belongs_to :user
end

User 保存的时候不会自动保存关联 id. 研究了 mongoid 的代码发现, mongoid 在 Model.new 的时候,id 就已经设置值了,而 mongoid_auto_increment_id 在调用 as_document 时才会设置 id ,所以出现关联 id 不会自动保存的问题。

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid using {...} for multi-line blocks.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line is too long. [105/80]
Use the new Ruby 1.9 hash syntax.
Space inside } missing.
Space inside { missing.

@rubyonme rubyonme changed the title fix-accepts_nested_attributes_for Fix accepts_nested_attributes_for Nov 11, 2015
@huacnlee
Copy link
Owner

不能改变生成 Id 的时机,自增 Id 不同于 ObjectId 是有限的空间,new 就用掉会浪费掉,还有很多连带的未知问题

@huacnlee
Copy link
Owner

想想别的方法

@rubyonme
Copy link
Author

也是这个道理。不过目前没有想出什么更好的办法,我再想想吧

@rubyonme
Copy link
Author

accepts_nested_attributes_for 是使用 autosave 机制,使用 after_save 保存,问题是 after_save 的时候 id 已经生成了,但是 autosave 里的 relation 还是没有 id 的,@huacnlee ,知道是什么原因吗?

def autosave(metadata)
  if metadata.autosave? && !metadata.embedded?
    save_method = :"autosave_documents_for_#{metadata.name}"
    define_method(save_method) do

      if before_callback_halted?
        self.before_callback_halted = false
      else
        __autosaving__ do
          if relation = ivar(metadata.name)
            options = persistence_options || {}
            if :belongs_to == metadata.macro
              relation.with(options).save if changed_for_autosave?(relation)
            else
              Array(relation).each { |d| d.with(options).save if changed_for_autosave?(d) }
            end
          end
        end
      end
    end

    after_save save_method, unless: :autosaved?
  end
end     

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants