干一个助手:包装form_for并访问本地表单变量 [英] DRYing up a helper: wrap form_for and access local form variable

查看:72
本文介绍了干一个助手:包装form_for并访问本地表单变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试干燥一堆表单代码,这些代码在每个表单的末尾都有重复的字段集.我写了一个围绕form_for rails helper的helper.但是我开始迷失在飞来飞去的所有不同范围...

I am trying to DRY up a bunch of forms code that has a repeating set of fields appearing at the end of each form. I wrote a helper that wraps around the form_for rails helper. But I'm starting to get lost in all the different scopes that are flying around...

我的助手是这样的:

def simple_form_helper(record_or_name_or_array, *args, &proc)
    options = ... # overriding some options, not relevant
    form_for(record_or_name_or_array, *(args << options.merge(:option => "blah")) , &proc)

    # i wish to access  &proc and append the call to render 
    # to within &procs scope (to access block local variable)
    concat render('shared/forms/submit')     # this obv does not work

end

在shared/forms/_submit.erb中,我有一堆字段,并提交了一堆模型共有的按钮.因此,我希望在form_for的范围内进行渲染,以便可以访问f.

in shared/forms/_submit.erb i have bunch of fields and submit buttons that are common to a bunch of models. So I want this to be rendered from within form_for's scope so that there is access to f.

 f.text_field :foo
 f.hidden_field :bar
 f.submit "Save"

想法是像在视图中那样使用它:

The idea is to use it like so in the views:

simple_form_helper :object do |f|
  f.text_field :name
  f.text_field :description
  f.text_field :other_field
  # want common fields and submit button appended here

  # I could just call render("shared/forms/submit") here
  # but that does not seem very DRY. Or am I too unreasonable?
end

因此,它的功能类似于旧的form_for:为具有特定字段的:object创建表单.然后在局部模型中附加在一系列模型中通用的字段.

So it functions like the good old form_for: makes a form for some :object with fields specific to it. And then appends the partial with fields that are common across a bunch of models.

有没有办法做到这一点?也许,有更好的方法吗?

Is there a way to accomplish that? Perhaps, there's a better way?

谢谢!

推荐答案

很确定这会起作用

def simple_form_helper(record_or_name_or_array, *args)
   options = ... # overriding some options, not relevant
   form_for(record_or_name_or_array, *(args << options.merge(:option => "blah"))) do |f|
       yield f if block_given?
       concat f.text_field :foo
       concat f.hidden_field :bar
       concat f.submit "Save"  
   end
end

,如果您不需要添加任何字段,也可以无障碍调用simple_form_helper :object

and you can also call simple_form_helper :object without a block if you don't need to add any fields

这篇关于干一个助手:包装form_for并访问本地表单变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆