2

Following Railscasts #197, would anyone know how to add a class to the link_to that's calling a js function?

<%= link_to_add_fields "Add Recipient", f, :recipients %>

_

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));
}

I've tried a lot of different things but haven't found anything that worked. Like, I assume it should be something like:

<%= link_to_add_fields "Add Recipient", {f, :recipients}, :class => "button_add" %>

which would produce (with or without brackets around the two object being passed to the function:

undefined method `object' for #<Hash:0xaa8c320>

Ruby 1.8.7 / Rails 2.3.5

1 Answer 1

3

I would extend method with css_class parameter

module ApplicationHelper

    def link_to_add_fields(name, f, association, css_class)
        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)}\")", :class => css_class)
    end
end

then i assume you can call the helper method as follow

<%= link_to_add_fields "Add Recipient", f, :recipients, "button_add" %>

I have not tried that, but this resource speak clearly

apidock link_to_function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.