In this conclusion to a four-part series on building an online bookstore application in Ruby-on-Rails, you'll learn how to edit and delete authors, and more. This article is excerpted from chapter two of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
We try to load the edit page for author 1 and test that the form has input fields with correct preset values. After running the test and finding it running red, we implement the edit interface. We first set the needed values in theeditaction inapp/controllers/admin/author_controller.rb:
def edit @author = Author.find(params[:id]) @page_title = 'Edit author' end
We use the normalActiveRecord findmethod to fetch theAuthorobject with theidthat was passed with the URL. Then we populate the page title, just as we did with thenewpage. The view fileapp/views/admin/author/edit.rhtmllooks pretty much the same asnew.rhtml, with the exception that the form action isupdateinstead ofcreatethis time. Note that we use the same partial template to output the actual form fields as on thenewpage.
In the update, we post the form to theupdateaction, and after that, check that we are redirected and, more important, that the first name of the author is really changed. The test doesnít yet pass, of course, so letís open theauthor_controller.rbfile again and implement theupdate action.
def update @author = Author.find(params[:id]) if @author.update_attributes(params[:author]) flash[:notice] = 'Author was successfully updated.' redirect_to :action => 'show', :id => @author else @page_title = 'Edit author' render :action => 'edit' end end
You can see that the action is more or less similar to thecreateaction, with the distinction that, this time, we use theupdate_attributesmethod to update the@authorobject. It updates the attributes of the object with the values it gets from the form parameters, and after that, it callssaveimplicitly. Just likesave, it returnsfalseif saving the object didnít succeed.
We can now run the test file again, and see that everything passes just fine.