0

A collection of objects are found and are sorted on the basis of a unique value

@sections = Section.where('id IN (?)', @sections_uniq).to_a

This is then meant to be presented in the view as tabs (using foundation), with one tab for each unique value

<% @sections.each do |section, index| %>
   <li>
      <input type="radio" name="tabs" id='tab<%= index %>' />

the index value is necessary to create on tab per unique value.

No version of <%=or #{...} seems to work. What is the syntax to generate that index value ( i.e. id='tab0', id='tab1'...) within the quoted value of the HTML tag?

10
  • 1
    You need each_with_index, since each doesn't yield the index by itself. Commented Aug 23, 2018 at 10:01
  • Right, but this still generates Enumerator:0x007ffb2c1d0d60type result Commented Aug 23, 2018 at 10:03
  • Can you show that result? Commented Aug 23, 2018 at 10:06
  • <input type="radio" name="tabs" id='tab#&lt;Enumerator:0x007ffb2cc8dc58&gt;' /> Commented Aug 23, 2018 at 10:08
  • And your code in the view, remains the same? Commented Aug 23, 2018 at 10:09

1 Answer 1

1
<% @sections.each.with_index do |section, index| %>

The collection needs first to be converted to enumerator. And that can be done via the help of .to_enum, .each, or .map

update, second alternative

As pointed out in comments below defining in controller

@sections = Section.where('id IN (?)', @sections_uniq)

without a suffix, and in the view.

<% @sections.each_with_index do |section, index| %>

works just as well.

Thus the solution depends on what one will do with the array, aside from the initial case (as described above), within the action.

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

3 Comments

What do you get by removing .to_a on @sections?
I got the same result using all . Had not thought of removing the array definition suffix... Removing the suffix and retaining each_with_indexfor invoking the array works as well.
You can easily use each_with_index if Section.where('id IN (?)', @sections_uniq) returns a Section::ActiveRecord_Relation.

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.