-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
-
None
I use mongoid_autoinc_id gem to generate auto increment id, when i use accepts_nested_attributes_for, it can't get attachable_id, it looks like "attachable_id"=>nil,
``ruby
module MongoidAutoincId
module AutoIncrement
extend ActiveSupport::Concern
included do
field :_id, :type => Integer
before_create :inc_id
end
def inc_id
self.id = Mongoid.default_session.command(findAndModify: "mongoid_autoinc_id",
query: {_id:self.class.name},
update: {"$inc" => {next:1}},
new: true,
upsert: true)["value"]['next'].to_s
end
end
end
Mongoid::Document.send :include, MongoidAutoincId::AutoIncrement
class Photo
include Mongoid::Document
field :title, type: String
field :description, type: String
has_many :attachments, :as => :attachable, dependent: :destroy
accepts_nested_attributes_for :attachments , :allow_destroy => true, :reject_if => lambda
end
encoding: UTF-8
class Attachment
include Mongoid::Document
field :file, type: String
field :attachable_type, type: Integer
field :description, type: String
belongs_to :attachable, :polymorphic => true
mount_uploader :file, FileUploader
end
INSERT database=bdwsw_development collection=attachments documents=[
{"description"=>"test", "attachable_id"=>nil, "attachable_type"=>"Photo", "attachable_field"=>:attachments, "file"=>"9fb6c409ab.jpg", "_id"=>60}] flags=[] (0.0001ms)