Helper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
def add_phone_link(name) link_to_function "Add another" do |page| page.insert_html :bottom, :phones, :partial => 'phone', :object => Phone.new end end def remove_phone_link(name) link_to_function "Remove" do |page| page["phone_#{params[:index]}"].remove end end def add_email_link(name) link_to_function "Add another" do |page| page.insert_html :bottom, :emails, :partial => 'email', :object => Email.new end end def remove_email_link(name) link_to_function "Remove" do |page| page["email_#{params[:index]}"].remove end end
Refactorings
No refactoring yet !
Jason Dew
October 16, 2007, October 16, 2007 23:25, permalink
I don't see where you use the argument to these functions.... Anyway, here's my shot at refactoring
1 2 3 4 5 6 7 8 9
def add_associated_link(model_name, label = "Add another") link_to_function label do |page| page.insert_html :bottom, model_name.pluralize, :partial => model_name, :object => model_name.camelize.constantize.new end end def remove_associated_link(model_name, label = "Remove") link_to_function label {|page| page["#{model_name}_#{params[:index]}"].remove } end
Etandrib
October 17, 2007, October 17, 2007 20:50, permalink
Here is where I call the links. For some reason I get an error with the new code saying the following:
Showing app/views/people/_fields.rhtml where line #11 raised: "Add another" is not a valid constant name!"
_fields
1 2 3 4
<h3>Phone Numbers</h3> <%= render :partial => 'phone', :collection => @person.phones %> <%= add_associated_link "Add another" %>
namxam
October 17, 2007, October 17, 2007 21:02, permalink
If you look a little bit closer, you will see, that the first param to Jason's refactored code is the model name, so your call is wrong.
1
<%= add_associated_link 'Email', "Add another" %>
research papers
January 22, 2010, January 22, 2010 16:10, permalink
Thanks for posting this. very informative. I'd be able to use this codes in my program. Thanks again.
1 2 3 4 5
for (i=0 i<3 i++); { i.print = "Hello"; } i--;
I've got a bunch of add and remove functions that would be nice to refactor without all the duplication. Lets see what you can do! Thanks!