lewstherin
lewstherin

Reputation: 73

simple_form_for: Removing root model name from params

When I create a form using simple_form_for @model, upon submit the post params has all the attributes grouped under params[model]. How do I get simple_form to drop this grouping and instead send it directly (under params root)?

<%= simple_form_for @user, do |f| %>
<%= f.input :name %>
<%= f.input :password %>
<%= f.submit %>

Now the name and password attributes would normally be sent under params[:user][:name], params[:user][:password] etc. How do I get simple_form to post these as params[:name], params[:password] etc.?

Thanks!
Ramkumar

ps: In case you are wondering why I need this, the bulk of my app is to serve as an API and I have built a set of methods to validate a request which expect some attributes to be in root. In a rare instance (forgot password), I actually need to present a form and I am looking for a way to use these methods.

Upvotes: 5

Views: 1680

Answers (2)

jethroo
jethroo

Reputation: 2124

you can explicitly define the name for an input by passing input_html to it:

  input_html: { name: :name }

(needed this myself for sending an resource to a thirdparty endpoint with redirect to my side which relied on the plain attribute names, but i actually wanted not to built up label and input via the tags ;) )

also see simple form builder impl

Upvotes: 3

dpassage
dpassage

Reputation: 5453

Two ways I can think of:

The first is, don't use simple_form to build your form, but do it by hand or with the form_tag and *_tag methods. These will allow you to more closely specify what parameters are used in your form.

If you want to keep simple_form, though, then have it call a different controller action. Refactor the controllers to strip out the logic into a separate method. Something like:

class UsersController
  def create_from_api
    controller_logic(params)
  end
  def create_from_form
    controller_logic(params[:user])
  end
  def controller_logic(params)
    [actual work happens here]
  end
end

Upvotes: 1

Related Questions