Rails CRUD使用单个Partial的所有视图的按钮

时间:2013-03-18 16:40:21

标签: ruby-on-rails ruby controller views crud

Rails新手在这里。

我想使用单个部分来在所有视图上创建我的CRUD按钮,而不管控制器如何。所以这就是我迄今为止所做的工作。在我的控制器中,我有:

information_controller.rb

class InformationController < ApplicationController
  before_filter :set

  def set
    #Set Paths
    @new_path = new_information_path
    @edit_path = edit_information_path
  end

  #Then normal index, show, etc definitions follows

end

我将以索引和编辑页面为例。

index.html.haml

-@operation = "index" #To let partial know what page it is in
-render 'form', operation: @operation

edit.html.haml

-@operation = "edit"
- render 'form', operation: @operation

然后,在我的部分形式中,我有:

_form.html.haml

.form-inputs
  .container-fluid
    .span8
      .simple_form_for @foo do |f|
        =f.input :title, as: :string
        =render 'controls', f: f, operation: @operation

并且在我的控件窗体中,无论控制器如何,它都只显示CRUD按钮,我有:

_controls.html.haml

-if(operation=="new")
  link_to "Create", @new_path, class: "btn btn-success"
-else
  -if(operation=="edit")
    =f.submit "Update"
  -else
    .span3
      %table
        %tr
          %td=link_to "Edit", @edit_path(f), class: "btn btn-primary"
          %td=link_to "Delete", f, confirm: "Are you sure", method: :delete, class: "btn btn-danger"        

因此,这适用于加载“编辑,删除和创建”按钮的索引页面。但我不知道如何将控制器中的edit_information_path正确分配给@edit_path,因为这需要编辑参数'f'。

赋值@new_path = new_information_path有效,但@edit_path需要'f'。任何技巧?

1 个答案:

答案 0 :(得分:1)

试试这个:

link_to "Edit",{:controller => params[:controller], :action => :edit, :id => f.object.id}, class: "btn btn-primary"

或:

link_to "Edit",{:controller => controller_name, :action => :edit, :id => f.object.id}, class: "btn btn-primary"