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

后端 未结 2 1831
终归单人心
终归单人心 2021-01-16 18:29

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 helpe

相关标签:
2条回答
  • 2021-01-16 18:48

    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

    0 讨论(0)
  • 2021-01-16 18:55

    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 讨论(0)
提交回复
热议问题