开发者

DRYing up a helper: wrap form_for and access local form variable

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...

My helper goes something like this:

def simple_form_helper(record_or_name_or_array, *args, &a开发者_运维知识库mp;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

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

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?

Thanks!


pretty sure this would work

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

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


You could also have used a partial layout, here is the syntax for reference.

Layout partial:

<%= form_for(record_or_name_or_array, :class => my_local_variable) do |f| %>
  <%= f.hidden_field :some_field %>

  <%= yield f %>

  <%= f.submit "Save" %>
<%- end %>

Template or partial where to use layout:

<%= render :layout => "partial_layout_name", :locals => {:my_local_variable => value} do |f| %>

  <%= f.text_field :more_fields_here %>

<%- end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜