更改form_for提交的ActiveModel

时间:2015-03-17 22:49:46

标签: ruby-on-rails form-for

我有一个表单,允许我的管理员创建用户。我正在使用STI,因此管理员可以指定AdminUser的类型。如果我提交包含无效信息的表单并且保存失败,我的控制器将使用@user模型重新呈现表单,如下所示:

def create
    @user = User.new(user_params)

    if @user.save
      redirect_to admin_users_path, notice: "#{@user.first_name} #{@user.last_name} user created"
    else
      render :new
  end
end

我遇到的问题是,提交按钮现在提交了一个哈希,其中包含admin而不是user的信息,这意味着我将parael白名单的方法无效:

def user_params
    params.require(:user).permit(:email, :first_name, :last_name, :password,
      :password_confirmation, :type, :role_id)
end

有没有办法可以修改提交按钮,使其提交为user而不是admin

带按钮的视图:

.col-md-6.col-md-offset-3
  = form_for [:admin, @user], html: {role: :form}, url: admin_users_path do |f|
    - if @user.errors.any?
      %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg

    .row
      #first_name.form-group
        = f.label :first_name
        = f.text_field :first_name, autofocus: true, class: 'form-control'

    .row
      #last_name.form-group
        = f.label :last_name
        = f.text_field :last_name, class: 'form-control'

    .row
      #email.form-group
        = f.label :email
        = f.email_field :email, class: 'form-control'

    .row
      .col-md-6
        #user_type.form_group
          = f.label :type
          = f.select :type, options_for_select(%w{Customer Admin}, selected: @user.type), class: 'form-control'

      .col-md-6
        #admin_role.form-group
          = f.label :role
          = f.collection_select :role_id, Role.all, :id, :name

    .row
      #password.form-group
        = f.label :password
        = f.password_field :password, class: 'form-control'

    .row
      #password_confirmation.form-group
        = f.label :password_confirmation
        = f.password_field :password_confirmation, class: 'form-control'

    #submit.actions.text-center
      = f.submit

1 个答案:

答案 0 :(得分:1)

您可以在as: :user中添加form_for选项。 Rails docs中的更多细节。