Skip to content

Commit

Permalink
[EPIC P] Add api for batch creation.
Browse files Browse the repository at this point in the history
  • Loading branch information
btelles committed Mar 28, 2012
1 parent 0d2395a commit cc93d4f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
28 changes: 25 additions & 3 deletions app/controllers/bicycles_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
11 changes: 11 additions & 0 deletions spec/api/bicycle_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit cc93d4f

Please sign in to comment.