Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[EPIC P] Add api for batch creation.

  • Loading branch information...
commit cc93d4fbf2eb474b944bf4b6d1988c93c22aa1da 1 parent 0d2395a
@btelles authored
Showing with 36 additions and 3 deletions.
  1. +25 −3 app/controllers/bicycles_controller.rb
  2. +11 −0 spec/api/bicycle_spec.rb
View
28 app/controllers/bicycles_controller.rb
@@ -10,10 +10,14 @@ def index
end
def create
- if bicycle.save
- redirect_to bicycle, notice: 'Bicycle was successfully saved.'
+ if params[:bicycle].present?
+ if bicycle.save
+ redirect_to bicycle, notice: 'Bicycle was successfully saved.'
+ else
+ respond_with bicycle
+ end
else
- respond_with bicycle
+ batch_create
end
end
@@ -23,4 +27,22 @@ def destroy
bicycle.destroy
redirect_to bicycles_url
end
+
+ def batch_create
+ if params[:bicycles].present?
+ bikes = []
+ all_saved = false
+ ActiveRecord::Base.transaction do
+ params[:bicycles].each do |bicycle_hash|
+ bikes << Bicycle.new(bicycle_hash)
+ end
+ all_saved = bikes.all? { |bike| bike.save}
+ end
+ all_saved ? response.status= 200 : response.status= 422
+ render :text => ''
+ else
+ response.status= 422
+ render :text => "Please provide a bicycle or a list of bicycles"
+ end
+ end
end
View
11 spec/api/bicycle_spec.rb
@@ -28,4 +28,15 @@ def json_response
post '/bicycles', {:bicycle => {:name => 'my first bike', :wheels_attributes => [{:name => 'my first wheel'}]}}
Bicycle.first.wheels.first.name.should == 'my first wheel'
end
+
+ it "can create multiple bicycles in one request" do
+ post '/bicycles', {:bicycles => [{:name => 'my first bike', :wheels_attributes => [{:name => 'my first wheel'}]},
+ {:name => 'my second bike', :wheels_attributes => [{:name => 'my second wheel'}]}]}
+ names = Bicycle.all.map(&:name)
+ names.should include('my first bike')
+ names.should include('my second bike')
+ wheels = Bicycle.all.map(&:wheels).flatten.map(&:name)
+ wheels.should include('my first wheel')
+ wheels.should include('my second wheel')
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.