【问题标题】:Rails 4 nested attributes link_to_functionRails 4嵌套属性link_to_function
【发布时间】:2014-04-14 08:12:23
【问题描述】:

我正在制作一个简单的应用程序,它应该使用 rails 4 动态删除字段,我基本上是按照 rails cast tutorial 这样做的,但它在 rails 3 中,我设法解决了大部分问题,感谢上帝,但我被困在了这个,删除链接正确显示它只是不起作用!

当我转到localhost:3000/survey/new 时,一切看起来都很好,删除链接也应该是这样的

当我点击删除网址时,只需将localhost:3000/survey/new 更改为localhost:3000/survey/new#

这是我的代码的一部分,我认为它与删除链接有关

#_form.html.erb
<%= f.fields_for :questions do |ff| %>
<div class="field">
<%= render 'question_fields', :f => ff %>
</div>
<% end %> 

#_question_field.html.erb
<div class="field">
<p>
<%= f.label :content , "question"%><br>
<%= f.text_area :content %>
<%= link_to_remove_fields "remove", f %>
</p>
</div>

module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
end

#application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).parent(".fields").hide();
}

任何帮助,因为我不知道该做什么或缺少什么

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-4 nested-attributes link-to-function


    【解决方案1】:

    Railscast 有几个缺陷 - 最突出的是它只允许将单个表单元素附加到页面(它使用表单元素预加载 JS 链接并不断将相同的元素放在页面上——问题是这个元素与其他人具有相同的id

    一个better tutorial can be found here (uses child_index)


    我强烈建议您查看Cocoon gem

    您将能够通过上面的链接看到它是如何工作的,但最重要的是,您将能够使用它来调用尽可能多的新表单元素:link_to_add_associationlink_to_remove_association

    【讨论】:

    • cocoon 作为输出是惊人的,但它在 haml 中:/
    • 我在 ruby​​ 方面不太好,这是我第二周学习它,我希望我能找出我的代码中的错误,非常感谢你的回答:)
    • 没问题! Cocoon 也可以在erb 工作,对吗? github.com/nathanvda/cocoon/wiki/ERB-examples
    • 教程链接已损坏,仅供参考
    • Cocoon 不需要 HAML。如果您想使用 ERB,请使用 HAML 教程 (haml.info/tutorial.html) 帮助您将 HAML 示例代码转换为 ERB。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多