Forcing simpleForm to use the superclass instead of the subclass name

210 views
Skip to first unread message

Mohamad El-Husseini

unread,
Aug 7, 2012, 2:53:44 PM8/7/12
to plataformate...@googlegroups.com
I'm using simpleForm with STI and I'm having a hard time. Basically, I have an update action that I want to use to handle user updates at the superclass level. The users table has a type column which can be nil or Owner.

Updating normal users works well. However, when I load a user that happens to be type = "Owner", simpleForm uses the subclass name in the form. So <input name="user[name]" becomes <input name="owner[name]"...

When the params get posted to the update action, the controller is expecting params[:user], but if the user.type == "Owner", params show an "owner" object instead, and the update action fails.

Any idea how to get around this? I highlighted the differences in the params below:

Form:
      = simple_form_for @user, html: { class: 'form-horizontal' }) do |f|
        = render 'error_messages', object: @user
        = render 'user_fields', f: f
        .form-actions
          = f.submit class: 'btn btn-large btn-primary'

When editing a user.type = nil, the params appear as such:

user: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  name: Mini Mouse
  email: mi...@disney.com
  password: '121212'
  password_confirmation: '121212'
commit: Update profile
action: update
controller: users
id: '6'

When editing a user.type = "Owner"

owner: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  name: Me
  email: m...@me.com
  password: '121212'
  password_confirmation: '121212'
commit: Update Owner
action: update
controller: users
id: '5'

Users controller:

  def update
    if @user.update_attributes(params[:user])
      flash[:success] = t 'users.edit.flash_success'
      sign_in @user
      render 'edit'
      # redirect_to @user
    else
      flash.now[:error] = t 'users.edit.flash_error'
      render 'edit'
    end
  end

Carlos Antonio da Silva

unread,
Aug 10, 2012, 11:50:41 PM8/10/12
to plataformate...@googlegroups.com
This happens due to the conversion from the object's "naming" to the parameter. To get around that and enforce a particular naming, you just have to give the :as option to the form call:

    form_for @user, as: :user ….

This is how Rails handles naming, it's not a particular SimpleForm functionality. If you have any other doubt, please feel free to send to the list.

Cheers.

-- 
At.
Carlos Antonio

Reply all
Reply to author
Forward
0 new messages