Rails form_for条件参数

时间:2013-09-03 14:16:37

标签: ruby-on-rails ruby forms conditional form-for

我有一个表格,定义如下:

form_for(@model) do |f|
    # Really a lot happens here 
end

我想知道是否有任何方法可以调整第一行:form_for(@model)

首先,我可以使用辅助函数:

def my_form
   if some_condition
      form_for(@model)
   else
      form_for [@model, @nested_model]
   end
end

然后将其嵌入我的表单调用中。像这样:

my_form do |f|
    # Really a lot happens here 
end

但是,我得到“ No block given ”错误。有人可以指出 - 为什么以及如何解决它?也许我还可以使用其他方法吗?

不要问我为什么需要它。只是为了尽可能保持干燥。表格应该是可重复使用的,你知道:D

1 个答案:

答案 0 :(得分:2)

您需要将阻止传递给my_form。这样做的方法是在您想要块的位置包含yield

def my_form
   if some_condition
      form_for(@model) { |f| yield f }
   else
      form_for [@model, @nested_model] { |f| yield f }
   end
end

这应该是您在视图中传递的块:

my_form do |f|
    # Really a lot happens here 
end