Jonathan Tuzman
Jonathan Tuzman

Reputation: 13262

Can't dynamically add an id to div tag in rails helper

I'm having a very weird problem. Here's my view:

<h1>All Deals</h1>

  <%= sanitize print_grouped_deals(@deals) %>

Here's my deals_helper.rb

  def print_grouped_deals(grouped_deals_by_date)
    grouped_deals_by_date.map do |(date, deals)|
      %(<div id='#{date.to_s}-deals'>
        <h3>#{brief_time date}</h3>
          #{deal_paragraphs_for_group(deals)}</div>)
    end.join
  end

  def deal_paragraphs_for_group(deals)
    deals.map do |deal|
      %(<p>#{"<span class='warning'>POSSIBLY EXPIRED! -</span>" if deal.probably_expired?} #{link_to deal.headline, deal}</p>)
    end.join
  end

Of note is the 3rd line in the first method in the second snippet. I cannot get it to add an id to my div tag! If I change <div id='#{date.to_s}-deals'> to <div class='#{date.to_s}-deals'> it adds the class no problem but if I keep it as id= then it just creates a simple <div> tag with no attributes.

Lest we imagine it's something to do with generating multiple divs with ids (although the ids will be different), I've also tried generating a simple <div id="thing" /> from the helper, and I get the same empty div tags as a result.

WTF?

Upvotes: 3

Views: 431

Answers (1)

You have to pass a whitelist of attributes to the sanitize helper https://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize

To allow id attribute

<%= sanitize print_grouped_deals, attributes: %w(id) %>

To set the default allowed tags or attributes across your application

# In config/application.rb
config.action_view.sanitized_allowed_tags = ['div', 'h3']
config.action_view.sanitized_allowed_attributes = ['id', 'class']

Upvotes: 1

Related Questions