Created
August 2, 2012 19:38
-
-
Save napcs/3240002 to your computer and use it in GitHub Desktop.
fields_for counter?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
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.
#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.
What about a counter
helper method that keeps count in an instance variable? You could keep your view as-is, minus the dirty bits.
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
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.