如何使用form partial for new和edit actions with admin routes?

时间:2012-11-25 13:31:07

标签: ruby-on-rails ruby-on-rails-3 forms

如何为该部分表单设置网址,以便能够将其用于createupdate操作。

现在我必须设置两个网址:admin_faculty_path updateadmin_faculties_path create操作。

# admin/faculties/_form.html.haml
= simple_form_for @faculty, html: { multipart: true, class: 'form-horizontal' } do |f|
  = f.input :department_id, as: :hidden, input_html: { value: params[:department_id] } if params[:department_id]
  = f.input :name
  = f.input :name_en
  = f.submit

路线:

admin_faculties    POST   /admin/faculties(.:format)              admin/faculties#create
new_admin_faculty  GET    /admin/faculties/new(.:format)          admin/faculties#new
edit_admin_faculty GET    /admin/faculties/:id/edit(.:format)     admin/faculties#edit
admin_faculty      GET    /admin/faculties/:id(.:format)          admin/faculties#show
                   PUT    /admin/faculties/:id(.:format)          admin/faculties#update

控制器:

# faculties_controller.rb
  def new
    @faculty = Faculty.new
  end

  def create
    @faculty = Faculty.new(params[:faculty])

    if @faculty.save
      redirect_to admin_departments_path,
        notice: t('activerecord.successful_save_data')
    else
      flash[:error] = t('activerecord.save_data_error_html')
      render 'new'
    end
  end

  def edit
    @faculty = Faculty.find(params[:id])
  end

  def update
    @faculty = Faculty.find(params[:id])

    if @faculty.update_attributes(params[:faculty])
      redirect_to admin_departments_path,
        notice: t('activerecord.successful_save_data')
    else
      flash[:error] = t('activerecord.save_data_error_html')
      render 'edit'
    end
  end

1 个答案:

答案 0 :(得分:1)

您需要将命名空间传递给表单:

simple_form_for [:admin, @faculty]

参见例如