2

I am using the Rails html helper to create a simple html structure with a label, a select and optgroups (this is the only slightly complicated part).

I then created a helper called resources_optgroup. I want an output like this:

<div>
    <label>Something</label>
    <select name="something">
        <optgroup label="something">
            <option value="1">something</option>
            <option value="2">something</option>
            <option value="3">something</option>
        </optgroup>
        <optgroup label="something">
            <option value="1">something</option>
            <option value="2">something</option>
            <option value="3">something</option>
        </optgroup>
    </select>
</div>

And this is my Rails code. I can't make both,the label and the select tags to work together. What is this?

def collection_link(item,site)
      content_tag :div, class: '' do
        label_tag item['title']

        content_tag(:select) do
            concat resources_optgroup site, Page
            concat resources_optgroup site, Category
            concat resources_optgroup site, Post
            concat resources_optgroup site, Product
            concat resources_optgroup site, Service
        end
    end
  end

1 Answer 1

2

Those methods return strings, and your method returns the last thing that is performed. If you want it all, you will need to concatenate your strings. This will likely lead to a mess of html_safe calls, and other ugliness. A better solution would be to move the HTML generation to a view partial, and render it from your helper. You can pass any calculated or variable information in as locals.


By request - if you really want to make this in a helper, without using view code (despite the fact that it is view code), you can do something like:

def collection_link(item,site)
  content_tag :div, class: '' do
    label_tag(item['title']) +

    content_tag(:select) do
        resources_optgroup(site, Page) +
        resources_optgroup(site, Category) +
        resources_optgroup(site, Post) +
        resources_optgroup(site, Product) +
        resources_optgroup(site, Service)
    end
  end
end

This will almost certainly create html escaping issues....

Sign up to request clarification or add additional context in comments.

2 Comments

but how should I do if I really wanted to concatenate all functions outputs?
@VictorFerreira I just found about about apidock.com/rails/ActionView/Helpers/OutputSafetyHelper/… , might be relevant in your case...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.