【问题标题】:Why isnt the the link to working in my js.erb file为什么我的 js.erb 文件中没有工作链接
【发布时间】:2012-02-15 02:51:15
【问题描述】:

我的 js.erb 文件中有这个

var cart_item = "<table id='something' style='width:100%'>"; 
cart_item += "<tr><td>";
cart_item += "<%= @contact.name %>";
cart_item += "<%= link_to_remote 'Delete', :url => {:controller => 'registrations', :action => 'destroy' %>";
cart_item += "</td>";
cart_item += "</tr></table>";

$("#cart").append(cart_item);

它只是挂起,但是当我注释掉 link_to_funtion 时,一切都很好。我什至试图将其设为 link_to,但它仍然挂起并且什么也不做......我错过了什么

【问题讨论】:

  • cart_item 字符串不会像调用 $("#cart").append(cart_item); 时那样通过 link_to_function 附加到 #cart 中。
  • 您应该更新您的问题以包含您正在使用的 Rails 版本。 link_to_remote 不久前就被弃用了——尽管你可以通过prototype_helpers gem 获得它

标签: javascript ruby-on-rails ruby ruby-on-rails-3 erb


【解决方案1】:

将所有这些提取到一个部分,称之为_cart_item.html.erb

<table id='something' style='width:100%'>
<tr><td>
<%= @contact.name %>
<%= link_to 'Delete', {:controller => 'registrations', :action => 'destroy', :id => @contact.id}, :remote => true %>
</td>
</tr></table>

然后,您的js.erb 文件将如下所示:

$("#cart").append(<%= escape_javascript(render(:partial => "cart_item")) %>);

但 Ryan Bigg 仍然是对的,你应该:

  • 使用 RESTful 路由和路由助手。
  • 对 AJAX 请求使用 :remote =&gt; true,就像我所做的那样。
  • 确保将id 传递给destroy 操作,以便它知道要销毁哪个对象。

【讨论】:

  • 感谢您提出将某些部分提取到部分的建议,这对我有用。在 js.erb 中使用 ruby​​ 有点混乱。
【解决方案2】:

四件事。

一:不需要:url 选项。您可以将哈希作为第二个参数传递给link_to_remote,它会起作用。

二:您应该为此使用 URL 助手。此外,如果您使用 destroy 操作,您可能需要传递一个 id。这意味着您将改为执行以下操作:

link_to_remote 'Delete', registration_path(id)

你会为此做类似resources :registrations 的事情。虽然,不确定您的应用程序中有哪些注册,所以我真的可以就此提出建议。

三:最重要的是,您缺少 link_to_remote 行上散列的结尾大括号。如果您忽略它,这会引发语法错误。

四:link_to_remote 在 Rails 3.0 中已弃用。你应该使用link_to 'Delete', registration_path(id), :remote =&gt; true

【讨论】:

  • 我认为它与链接或 js.erb 中的某些内容更相关....我将行更改为此进行测试,结果仍然相同 ---------- - cart_item += "";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多