Geoff Garside

Sep 27 2008

Rails f.submits

I’ve been using this sort of pattern for a while in my form partials. Because [Make Resourceful][m_r] provides a current_object method I usually pass this to form_for instead of a symbol matching the name of the instance variable. So I’ll have something like this

- form_for current_object do |f|
  = f.label :name
  = f.text_field :name
  = f.submit f.object.new_record? ? 'Create' : 'Update'

so that I can get the value of the submit tag to change properly based on if its a new or edit action. This of course looks horrible, so I’ve recently dug into Rails and written an extra method which is specifically designed for this case.

Now I’d love to take f.submit and make that capable of taking a few more arguments but supporting the current call sequence with the new is a bit complicated. So I called mine f.submits instead, if a better name could be had I’d love to hear it.

Basically it just does the same as the above form submit call, but internalises it. So without further ado, here it is f.submits

module ActionView
  module Helpers
    class FormBuilder
      def submits(create_value = "Create", update_value = "Update", options = {})
        value = @object.new_record? ? create_value : update_value
        submit(value, options)
      end
    end
  end
end

So instead of the

= f.submit f.object.new_record? ? 'Create' : 'Update'

we just have

= f.submits

and the method works out which we should be using, if you don’t want Create or Update you can call it like

= f.submits 'Create thing', 'Save thing'

and if you want to add options, like you would to f.submit you put them at the end, such as

= f.submits 'Create thing', 'Save thing', :class => 'submit_button'

I’m tempted to put together a patch for rails complete with tests and submit it for review and possible inclusion into rails, that’d be quite cool.

BTW I decided not to use an embedded gist this time as it doesn’t quite fit that well with Tumblr, I may change the previous entry.

Comments
blog comments powered by Disqus