2

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

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

结果,它用部分替换了整个页面。怎么了?

编辑一个

remote: true正如 Anchor 所说,添加到 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#download 作为 JS 参数处理:{"attachment"=>{"download_count"=>"175", "filename"=>"filename.doc", "id"=>"2fd9adbf6172740d46060000", "type"=> "appli"}, "user"=>"7fbceaa661727417f55e0000"} 渲染 users/_downloads.html.erb (60.7ms) 在 106ms 内完成 200 OK (Views: 63.1ms)

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

4

2 回答 2

1

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

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

有类似的东西

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

于 2013-10-22T06:10:38.057 回答
1

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

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

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

于 2013-10-20T07:20:48.270 回答