Rails通过link_to将本地参数传递到js中然后部分加载

发布于 2024-12-03 23:35:25 字数 887 浏览 1 评论 0原文

我正在尝试使用 link_to 将局部变量传递给局部变量。我尝试了很多不同的方法,但似乎不起作用。 js 文件加载部分没问题,只是没有局部变量。这就是我所拥有的,感谢您的指导!

_health.html.erb(这是联系人模型的index.html的一部分)

<% @comments = Comment.find_all_by_api(@api) %>
<%= link_to 'Read Comments', comments_path(:comments => @comments), :action => 'comments',  :remote => true %> 

comments.js.erb

$("#comments").html("<%= escape_javascript(render(:partial => 'comment', :locals => {:comments => :comments})) %>");

comment.html.erb

<% unless @comments.blank? %>
 <% @comments.each do |c| %>

   <%= c %><br />

 <% end %>
<% end %>

contacts_controller.rb

  def comments  
   respond_to do | format |  
      format.js {render :layout => false}  
   end
 end

I am trying to pass along a local variable to a partial using link_to. I have tried many different things, but it doesn't seem to work. The js file loads the partial fine, it just doesn't have the locals. This is what I have, thanks for any direction!

_health.html.erb (this is a partial on index.html of Contacts model)

<% @comments = Comment.find_all_by_api(@api) %>
<%= link_to 'Read Comments', comments_path(:comments => @comments), :action => 'comments',  :remote => true %> 

comments.js.erb

$("#comments").html("<%= escape_javascript(render(:partial => 'comment', :locals => {:comments => :comments})) %>");

comment.html.erb

<% unless @comments.blank? %>
 <% @comments.each do |c| %>

   <%= c %><br />

 <% end %>
<% end %>

contacts_controller.rb

  def comments  
   respond_to do | format |  
      format.js {render :layout => false}  
   end
 end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘味果▽酱 2024-12-10 23:35:25

部分不知道注释,因为您从未设置它们。控制器中的评论操作需要如下所示:(

def comments
   @comments = Comment.find(params[:id])
   respond_to do | format |

params[:id] 替换为路由中的适当参数)

您正在执行 AJAX 请求,并且由于 http 是无状态的,因此评论操作不知道有关任何先前请求的任何信息 - 这意味着来自 _health.html.erb 的评论对于控制器中的评论操作已不再存在。

The partial does not know about the comments because you never set them. The comments action in the controller needs to look like this:

def comments
   @comments = Comment.find(params[:id])
   respond_to do | format |

(replace params[:id] with the appropriate parameter from your route)

You're doing an AJAX request and since http is stateless, the comments action does not know anything about any previous requests - which means that the comments from _health.html.erb have ceased to exist for the comments action in the controller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文