封装两个form_for块的Helper方法

时间:2009-11-01 08:56:48

标签: ruby-on-rails form-for formbuilder

如何构建一个类似于

的辅助方法
-confirmation_for [@post, @comment] do |f|
  = f.confirm "Post"
  %p html here...
  = f.edit    "Edit"

并封装两种形式,如

-form_for [@post, @commment] do |f|
  = f.hidden_field :submission_state, :value => "confirmed"
  = f.submit "Post"
%p html here...
-form_for [@post, @commment] do |f|
  = f.hidden_field :submission_state, :value => "edit_requested"
  = f.submit "Edit"

1 个答案:

答案 0 :(得分:0)

如果不重新定义form_for,我认为没有办法准确找到你想要的东西。或者编写自己的版本。

你可以接近FormBuilders或Partials或Helpers,但这些概念都不能让你做你想做的事。

FormBuilder将允许您定义要在窗体上调用的方法,如确认和编辑,但它们将是同一窗体的一部分。除非你创建两个表单。

在相关的帮助文件中:

class ExampleFormBuilder < ActionView::Helpers::FormBuilder    

  def confirm
    hidden_field(:submission_state, :value => "confirmed") + "\n" + submit "Post"
  end

  def edit
    hidden_field(:submission_state, :value => "edit_requested") + "\n" + submit "Edit"
  end


end

样本用法:

- form_for [@posts,@comments], :builder => ExampleFormBuilder do |f|
  = f.confirm
- form_for [@posts,@comments], :builder => ExampleFormBuilder do |f|
  = f.edit

当与部分一起使用时,你可以做这样的事情

部分:

- form_for [@posts,@comments], :builder => ExampleFormBuilder do |f|
  = f.send(action)

观点:

= render :partial => :confirmation_for, :locals => {:action => :confirm}
= render :partial => :confirmation_for, :locals => {:action => :edit}

然后,您可以将两个部分调用捆绑到另一个部分。但这有点太过分了。