Is there a way to count the number of nested fields that have been added to a form, in Rails?
I currently have a form that allows the user to add or remove nested attributes.
The code is basically the same from the Railscast http://railscasts.com/episodes/196-nested-model-form-revised just changed slightly for my requirements (different controller and model names).
What I want to be able to do is count the number of sets of nested attributes that are currently in the form. Is there a way to do this in Rails or would I be better using jQuery?
I need to be able to access the value in the view.
Any help much appreciated. If you need to see the code, let me know.
jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
count--
$(this).prev('input[type=hidden]').val('1')
$(this).closest('.panel').hide()
$('#price').text(count)
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
count++
$('#price').text(count)
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
In the view I have set the count variable to 1, for testing purposes. I’m thinking that this needs to be set before the page loads as it is probably loading the javascript last, therefore not showing the initial count?
If you have an element in which you want to display the count variable, say
<div id="count"></div>, you can write$('#count').html(count)in the click function right after count gets updated.UPDATE:
for the initial count (before the user clicks the add/remove button), include the count in erb page template