Rails - 将一个CSS类添加到Link_to_(我的javascript函数)?

时间:2012-05-26 15:36:45

标签: ruby-on-rails

在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

1 个答案:

答案 0 :(得分: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

然后我假设您可以调用helper方法,如下所示

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

我没试过,但这个资源说得很清楚

apidock link_to_function