Skip to content

Instantly share code, notes, and snippets.

@napcs
Created August 2, 2012 19:38
Show Gist options
  • Save napcs/3240002 to your computer and use it in GitHub Desktop.
Save napcs/3240002 to your computer and use it in GitHub Desktop.
fields_for counter?
<fieldset>
<% counter = 1 %> <!-- FOR SHAME! -->
<%= f.fields_for :answers do |builder| %>
<div>
<%= builder.label :text, "Answer #{counter}" %>
<%= builder.text_field :text %>
<%= builder.label :correct, "Correct" %>
<%= builder.check_box :correct %>
<%= builder.label :_destroy, "remove" %>
<%= builder.check_box :_destroy %>
<% counter += 1 %> <!-- BOO!!! -->
<div>
<% end %>
</fieldset>
@napcs
Copy link
Author

napcs commented Aug 2, 2012

This code is just awful, but I need to put "Answer 1, Answer 2, etc" there. I've seen lots of docs that reference things like answers_counter but none of those work. I can't stand this code but it makes my test pass. I'd love to see a better solution.

This uses nested attributes, so there's a Question model with many answers.

@napcs
Copy link
Author

napcs commented Aug 2, 2012

Thanks to @reedy. Putting it back into a render partial, I have a variable called answer_fields_counter. I had tried answers_counter ,and answer_counter. But this works!

[EDIT] Wait... nope, that doesn't work. Ran tests again and getting "undefined method" error.

@karmajunkie
Copy link

#zero-based index, and you want one more than the existing answer set
(1..question.answers.count+2).each do |answer_index|
   <%= render :partial => 'answer_fields', :locals => { :answer_index => answer_index, :f => f } %>
end

I don't love it but maybe something like that? I wrote the above assuming you may want to output existing answers or something.

@blaix
Copy link

blaix commented Aug 2, 2012

What about a counter helper method that keeps count in an instance variable? You could keep your view as-is, minus the dirty bits.

@blaix
Copy link

blaix commented Aug 2, 2012

or counter(:name) so the helper can store multiple counters in a hash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment