Rails仅渲染部分负载

时间:2013-10-20 06:37:27

标签: javascript jquery ruby-on-rails

我想在点击链接后重新加载部分页面。假设我想实现一个点击计数器。这就是我所做的。

show.html.erb

<div id="downloads"><%= render(partial:'downloads', locals: {user: @user}) %></div>
_downloads.html.erb

中的

<% user.attachments.each do |attachment| %>
  <%= attachment['download_count'] %>
    <br>
  <%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}%>
<% end %>
show.js.erb

中的

$("#downloads").html("<%= escape_javascript(render('downloads', locals: {user: params[:user]})) %>")
files_controller.rb

中的

def download
  user = User.find(params[:user])
  # increasing attachment's dl count
  # ...
  render(:partial => 'users/downloads', locals: {user: user}, :layout => false)
end

结果它用partial替换整个页面。怎么了?

编辑一个

如Anchor所说,将remote: true添加到link_to。

<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, remote: true %>
files_controller.rb

中的

替换render(:partial => 'users/downloads', locals: {user: user}, :layout => false)
respond_to do |format|
  format.js {  render(:partial => 'users/downloads', locals: {user: user}, :layout => false)}
end

现在尝试点击链接:我的页面没有任何反应。虽然在控制台中:

  

由FilesController处理#下载为JS     参数:{“attachment”=&gt; {“download_count”=&gt;“175”,“filename”=&gt;“filename.doc”,“id”=&gt;“2fd9adbf6172740d46060000”,“type”=&gt;“appli “},”user“=&gt;”7fbceaa661727417f55e0000“}     呈现的用户/ _downloads.html.erb(60.7ms)   在106ms完成200 OK(浏览次数:63.1ms)

我认为我现在面临着一个javascript问题。

2 个答案:

答案 0 :(得分:1)

看起来您的控制器正在返回HTML响应而不是脚本响应。尝试添加参数:remote =&gt;在link_to中为true:

<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, :remote => true %>

并确保您的控制器在响应块中具有相应的format.js

答案 1 :(得分:1)

嗯,终于解决了我的问题。 我在我的控制器中替换了

render(:partial => 'users/downloads', locals: {user: user}, :layout => false) # rendering html:(

类似

format.js {render(users/show.js.erb)} # should render js!