Thursday, 14 January 2010

Transactions

Used them for the first time - and love them.
I have a situation where a job can have many editions. An edition has many pages. If you create a new page for a job, you must create it for every edition. Likewise if you delete a page from a job, you must delete it from every edition. You must never end up in a situation where one page is deleted from one edition, but for some reason it fails on the next one.
Enter transactions.

This is my destroy action (handled by jQuery rather than the inbuilt rails method)
def destroy
@page = Page.find(params[:id])
@pages = Page.find_all_by_job_id_and_page_name_or_no(@job.id, @page.page_name_or_no)
invalid = false
Page.transaction do
@pages.each do |page|
begin
page.destroy
rescue ActiveRecord::StatementInvalid
invalid = true
end
end
end
if invalid
respond_to do |format|
format.html { render :action => "new" }
format.js {render :text => "-1" }
format.xml { render :xml => @page.errors, :status => :unprocessable_entity }
end
else
respond_to do |format|
format.html { redirect_to(pages_url) }
format.js {render :json => @page.id.to_json }
format.xml { head :ok }
end
end
end


And it all works.

No comments:

Post a Comment