Rails noob here.
I've been searching on Google and StackOverflow for information in order to get the example used in Railscasts #197 to work but none of the links i've visited work with Rails 3.1!
When I click on the remove or add new fields button absolutely nothing happens. This is so frustrating :/
Anyone know why the code I've provided below isn't adding fields or removing fields dynamically like in the RailsCasts episode?
application_helper.rb
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '# {escape_javascript(fields)}')", :remote => true)
end
app.js
// delete characters on users#edit and users#new
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest("#character").hide();
}
// add character fields on users#edit and users#new
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
html
<div id="account">
<div class="field">
<%= f.label :account_name %><br />
<%= f.text_field :account_name %>
</div>
<div class="field">
<%= f.radio_button(:realm, "USWest") %>
<%= f.label(:realm, "USWest") %>
<%= f.radio_button(:realm, "USEast") %>
<%= f.label(:realm, "USEast") %>
<%= f.radio_button(:realm, "Europe") %>
<%= f.label(:realm, "Europe") %>
<%= f.radio_button(:realm, "Asia") %>
<%= f.label(:realm, "Asia") %>
</div>
<div class="field">
<%= link_to_add_fields "Add new account", f, :characters %>
</div>
<div class="field">
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</div>
<%= f.fields_for :characters do |builder| %>
<%= render "characters/char_fields", :f => builder %>
<% end %>
</div>