Camping CRUD for the Lazy

by Gregory Brown

In your views



def _time_entry_form(entry)
_form_for(entry,R(AddTimeEntry))
end

def _form_for(record,handler,options={})
attributes = record.attribute_names
if options[:only]
attributes = options[:only]
elsif options[:omit]
attributes -= options[:omit]
end
attributes -= ["id"]
form :action => handler, :method => 'post' do
attributes.each do |e|
p do
label "#{e}: ", :for => e
input :type => 'text', :name => e, :value => record.send(e)
end
end
input :type => 'submit', :value => "Submit"
end
end


In your controllers



class AddClient < R '/client/new'

def get
@client = Client.new
render :add_client
end

def post
Models::Client.create(input)
redirect ShowClients
end

end


Oh ye gods of camping.. what do you think?

8 Comments

zimbatm
2007-02-13 01:41:06
Nice :) you might want to make the id read-only. Also check the Camping::Base#errors_for method to print AR errors.


Cheers,
zimbatm

Michael Gorsuch
2007-02-13 04:31:43
I think this is damn cool stuff. Just add some error handling, and things are good.
Gregory
2007-02-13 06:54:24
Sweet... I'll update the article this evening to reflect that...
Greg
2007-02-13 12:15:50
instead of:


form :action => R(handler)


this really should build up the route externally and pass in the generated route, so that you can specify params.


I'll update the example later to reflect this...

Greg
2007-02-15 10:07:50
Okay, it is now dropping the id and expecting you to do the R() call externally.


Literally two minutes of hacking did not get me the answer of where I should stick the errors_for call.


I plan to generalize this a bit more and then maybe put a post on the camping wiki. (We should be able to pretty easily define what kinds of input fields are needed).


In the mean time, if someone shows me the right place for errors_for I'll update the article, otherwise I'll do so when I get back to the job that I used this code in :)


John
2007-02-21 11:44:51
Could some more detail be provided linking the actial CRUB to the code. This example seems like it is just about the smallest example without any comments.


I can see the Create, Retrieve?, Update?, Delete? where? thanks

Greg
2007-02-21 12:06:57
Hi John,


This code was indeed terse because it wasn't meant to be a tutorial.
I was mostly interested in what people thought of _form_for


My whole CRUD in my apps has become increasingly unconventional as I'm dealing with a large number of models. It still does not properly handle errors.


I've pasted it here, but you probably don't want to follow my lead in laziness. ;)


http://pastie.caboo.se/42016

John
2007-02-21 13:31:56
Sorry CRUD, not CRUB, doh!