Tip for DRY and RESTfull _form.rhtml

This tip has probably been suggested elsewhere but I’m not sure.
It concerns the C and U of the CRUD.
The default generated scaffold gives 4 methods and 3 views for updates
and creates. You have the combination of (new and create) + (edit and
update) methods in the controller. Then in the view you’ve got
new.rhtml, edit.rhtml and _form.rhtml which is appended to new or edit
according to which method you call. Not so DRY really.
‘Rails Recepies’ book gives a nice way to combine those in one method
but at least when ajax is used I found some glitches.
My idea is to give one method for create and another for update this
way :

def create
@model = Model.new
if params[:model]
@model.attributes = params[:model]
render :update=>… or whatever and return if @model.save

render :partial=>‘form’ # if no update.rjs or update.rhtml

def update
@model = Model.find param[:id]

#view _form.rhtml
<%form_for :model, @model, :url=>{:action=>controller.action_name}%>

#view create.rjs optional
#view create.rhml optional

The main idea is no matter what combination you use for rendering the
result (helpers, rjs, rhtml) you got rid of all the new and edit
methods and views. You just stay with plain create and update stuff
which makes it much less confusing thanks to the
“:action=>controller.action_name” trick in the _form.rhtml view.
Hope it’s usefull


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs