content_tag_for for combining more AR instances

Lately I found a behaviour in content_tag_for I was not expecting.

For the sake of explanation, let’s assume a web page that shows invoices and invoice_items. Instead of having one invoice per page, let’s say I have several invoices per page. Of course invoice_items can be repeated on the page, since many invoices can have the same item.

I was expecting it was possible to pass both the invoice and the invoice_item to content_tag_for, to have something like following:

  • ...
  • Surprisingly it’s not. Passing an array as the second argument allows for multiple tags to be created at once instead of taking it as the source of id and class.

    Of course, being invoice and invoice_item in a has many through condition, the answer would be to have an instance of the join model to be used to generate unique ids in the dom, but for instance this is not possible when using has_and_belongs_to_many association.

    I understand it wouldn’t make sense to add another option to that helper, it would be at confusing at least. I’m wondering if my thoughts find anybody in agreement that the API should be changed. The second argument array does not seem to be a big win as it is right now, having an outer cycle do the job is just two lines more (at most).

    We may take advantage of the major 4.0 release to break this behaviour.

    This behavior was added recently and it's meant to render a collection of
    records, so I don't think it's worth changing it. But, as you can see here:,
    you can add a third argument that's the "prefix" used in dom_id/dom_class,
    which means you could mix and match like this:

        content_tag_for :div, @invoice_items, dom_id(@invoice)

    Allowing you to use the collection of items in content_tag_for, prefixed by
    the dom_id of the current @invoice. I think that should work fine.