这里是Rails noob。
我一直在谷歌和StackOverflow上搜索信息,以使铁路#197中使用的示例能够正常工作,但是我访问过的链接都没有使用Rails 3.1!
当我单击“删除”或“添加新字段”按钮时,绝对不会发生任何事情。这真是令人沮丧
谁知道我下面提供的代码为什么不像RailsCasts节目那样动态地添加字段或删除字段呢?
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)
endapp.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>发布于 2011-08-01 12:49:38
我看不出必要的部分是:
render(association.to_s.singularize + "_fields", :f => builder)发布于 2011-09-03 05:33:15
好的,首先您需要确保您在application.js文件的头上使用了正确的rails 3.1include标记。在银幕上,他用的是旧的方式:
<%= javascript_include_tag :defaults, :cache => true %>新的方法是:
<%= javascript_include_tag "application" %>现在,在上述application.js文件中,您将看到下面的代码,不要删除这个,在资产管道中使用这些注释来包含jquery,它现在与rails捆绑在一起,而不是prototype.js。
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require_tree .看起来您的代码已经为jquery设置好了,因此,如果您想简化,只需将代码附加到注释下面的application.js文件底部,您就应该设置好了。
https://stackoverflow.com/questions/6894962
复制相似问题