Make Resourceful-ized form_for
One of the problems I’ve had recently is nested form partials in my Rails applications. I’ve got a controller which is always nested under another, it just logically makes sense that way. The problem I was having was that the rails form_for helper wanted to generate an un-nested url which the form would post to.
Now I also use make_resourceful with my controllers. This is important because it provides two routes helpers objects_path and object_path which are properly nested so I wanted form_for to really use these methods when autofilling the :url parameter of the form_for.
It took a bit of fiddling to get it worked out but I now have this
module ApplicationHelper
include ActionView::Helpers::FormHelper
def apply_form_for_options_with_make_resourceful!(object_or_array, options)
object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array
if object.respond_to?(:new_record?) && object.new_record?
options[:url] ||= objects_path
else
options[:url] ||= object_path
end
apply_form_for_options_without_make_resourceful!(object_or_array, options)
end
alias_method_chain :apply_form_for_options!, :make_resourceful
end
this sets up the :url option to the objects_path or object_path depending on if the model is a new record or not. It then calls the original apply_form_for_options! method for the remaining work to be setup.
This now properly the creates the form_for I require allowing me to completely embed the form in the _form partial and not setup independent forms in the new and edit templates.