Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use form_tag from within a helper?

I have a helper that I am using to generate a form. Parameters that are used to generate the form's fields are passed into the helper. I can't figure out how to use the block outside of a template.

For example:

def generate_form(path, fields)
    form_tag(path, method: :get) do
        # what do I do in here?
    end
end

When I render partials within the block, nothing appears in the rendered web page. If I join together a bunch of tags (field_tag, text_field_tag, etc.), then raw html appears on the page.

I am using Rails 3.1.0

like image 325
mushroom Avatar asked Sep 29 '12 18:09

mushroom


People also ask

What is Form_tag?

form_tag generates an HTML form for us and lets you specify options you want for your form. In the example below, we use the rails method, url_for, to create a URL we want the form to submit to.


1 Answers

Rails element helpers return strings, so you can do:

def generate_form(path, fields)
  s = form_tag(path, method: :get) do
    p = input_tag
    p << submit_tag #(everything will be wrapped in form tag)
    p #returns p from block
  end
  s.html_safe #returns s and avoids html escaping
end
like image 151
Mike Avatar answered Sep 28 '22 07:09

Mike