Rails通过link_to将本地参数传递到js中然后部分加载
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
部分不知道注释,因为您从未设置它们。控制器中的评论操作需要如下所示:(
将
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:
(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.