2

在 Railscasts #197 之后,有人知道如何将一个类添加到调用 js 函数的 link_to 吗?

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

我尝试了很多不同的东西,但没有找到任何有效的方法。就像,我认为它应该是这样的:

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

这将产生(在传递给函数的两个对象周围有或没有括号:

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

Ruby 1.8.7 / Rails 2.3.5

4

1 回答 1

2

我会用 css_class 参数扩展方法

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

然后我假设您可以按如下方式调用辅助方法

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

我没有尝试过,但这个资源说清楚

apidock link_to_function

于 2012-05-26T23:53:15.870 回答