I think everyone get’s it by now. In rubyland, we generally like Skinny Controllers and Fat Models. I just wanted to share a little before_filter I use on my CRUD controllers to make each action smaller even if it doesn’t make the whole controller smaller.
def load_record
unless params[:id].blank?
@record = SomeActiveRecordClass.find(params[:id])
end
if @record.nil?
@record = SomeActiveRecordClass.new
end
@record.attributes = params[:record] if params[:record]
end
I run this little before filter before new, create, edit, update, and destroy. In any of those actions you can depend on @record being set in the proper state, ready for saving, populating a form, or deleting.
It isn’t anything special just a way to keep boilerplate code out of the actions themselves.
Do you have any before_filter patterns? How do you keep your controllers looking slim and trim?
On an unrelated note, RideCharge, my employer, is actively seeking a QA Specialist. Our ideal QA person would be able to write automated tests in addition to normal QA activity. If you have anymore questions contact me schlueter [at] gmail [.] com.
Your code reminds me to a technique in “make_resourceful”. This great plugin for creating RESTful controllers is worth a look!
What about:
@record = (SomeClass.find_by_id(params[:id]) || SomeClass.new)
@Georg looked into “make_resourceful” looks interesting. I don’t think I can use it, since it claims it requires haml. Seems a little limited to me, but whatever.
@Mike Your way is slightly different that what I use. Mostly because if people are messing around with the urls and pass an id that doesn’t exist I want it to throw and exception, find_by_id doesn’t do that.