Skip to content

Commit 9dc6bb4

Browse files
committed
fix-accepts_nested_attributes_for
1 parent bab1f09 commit 9dc6bb4

File tree

3 files changed

+26
-21
lines changed

3 files changed

+26
-21
lines changed

lib/mongoid_auto_increment_id.rb

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,12 @@ def self.included(base)
6363
end
6464
end
6565

66-
# hack id nil when Document.new
67-
def identify
68-
Identity.new(self).create
69-
nil
70-
end
66+
alias_method :super_initialize, :initialize
7167

72-
alias_method :super_as_document, :as_document
73-
def as_document
74-
result = super_as_document
75-
if result[ID_FIELD].blank?
76-
result[ID_FIELD] = Identity.generate_id(self)
77-
end
78-
result
68+
def initialize(attrs = nil)
69+
@attributes ||= {}
70+
self[ID_FIELD] = Identity.generate_id(self)
71+
super_initialize attrs
7972
end
8073
end
8174
end

spec/base_spec.rb

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22

33
describe "Mongoid::AutoIncrementId" do
44
describe 'Base test' do
5+
before do
6+
Mongoid.purge!
7+
end
8+
59
after do
610
Post.delete_all
711
Tag.delete_all
812
User.delete_all
913
Log.delete_all
1014
end
1115

12-
it "new record Id will be nil" do
13-
expect(Post.new.id).to eq nil
16+
it "new record Id will be integer" do
17+
expect(Post.new.id).to be_a Integer
1418
end
1519

1620
it "does Id start from 1" do
@@ -39,9 +43,9 @@
3943
expect(p4.id - 2).to eq p2.id
4044
end
4145

42-
it "does return nil id when Model.new" do
43-
expect(Post.new.id).to eq nil
44-
expect(Post.new._id).to eq nil
46+
it "does return id when Model.new" do
47+
expect(Post.new.id).to be_a Integer
48+
expect(Post.new._id).to be_a Integer
4549
end
4650

4751
it "does can find data by String and Integer id" do
@@ -113,6 +117,17 @@
113117
expect(Log.where(:title => "test tag log").count).to eq 1
114118
expect(Log.where(:title => "test tag log").first._type).to eq "TagLog"
115119
end
120+
121+
context "when accepts_nested_attributes_for" do
122+
before { User.accepts_nested_attributes_for :posts }
123+
124+
it {
125+
user = User.new({"email"=>"[email protected]", "posts_attributes"=>{"0"=>{:title => "This is title!"}}})
126+
user.save
127+
user.reload
128+
expect(user.posts.size).to eq(1)
129+
}
130+
end
116131
end
117132

118133

@@ -134,4 +149,4 @@
134149
end
135150

136151
end
137-
end
152+
end

spec/spec_helper.rb

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,4 @@ def database_id
4040

4141
RSpec.configure do |config|
4242
config.mock_with :mocha
43-
config.after :suite do
44-
Mongoid.purge!
45-
end
4643
end

0 commit comments

Comments
 (0)