ruby-on-railsrubyactivemodelactionviewactionviewhelper

Rails form_for method not responding to html options


I have an active model model that I would like to use form_for with.

form_for(@item, url: (params[:action] == 'edit' ? api_item_path(datasheet_id: params[:datasheet_id], item_id: params[:item_id]) : api_items_path), html: {method: (params[:action] == 'edit' ? 'patch' : 'post')}) do |f|

I am choosing the url this way because the named paths have 'api_' prepended. (There is probably a nice way around this, but I hope that this is not part of my problem).

The problem is that the html option with the method key is not affecting the method of the form (which is always 'post').

The model respond_to? :persisted?, so ActionView is correctly naming the form (id="edit_item_xxx", class="edit_item"), but despite that the method remains post.

I hope there is something obvious that I am missing.

Here are the sources that I've used for info: https://github.com/rails/rails/blob/master/actionview/lib/action_view/helpers/form_helper.rb http://guides.rubyonrails.org/form_helpers.html


Solution

  • The method parameter should be outside of the html options hash:

    form_for(@item, url: (...), method: (...), html: {}) do |f|
    

    I would encourage you to write a helper or a custom form builder object. There is a lot going on for the view here, and it's easy to make mistakes, difficult to test.