Reputation: 760
I want to reload a part of page after a link clicked. Let's say I want to implement a click counter. Here's what I've done.
In show.html.erb
<div id="downloads"><%= render(partial:'downloads', locals: {user: @user}) %></div>
in _downloads.html.erb
<% user.attachments.each do |attachment| %>
<%= attachment['download_count'] %>
<br>
<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}%>
<% end %>
in show.js.erb
$("#downloads").html("<%= escape_javascript(render('downloads', locals: {user: params[:user]})) %>")
in 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
As a result it replaces whole page with partial. What's wrong?
EDIT ONE
Added remote: true
to link_to as Anchor said.
<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, remote: true %>
in files_controller.rb
replaced render(:partial => 'users/downloads', locals: {user: user}, :layout => false)
with
respond_to do |format|
format.js { render(:partial => 'users/downloads', locals: {user: user}, :layout => false)}
end
Trying to click link now: nothing happens at my page. Though in console:
Processing by FilesController#download as JS Parameters: {"attachment"=>{"download_count"=>"175", "filename"=>"filename.doc", "id"=>"2fd9adbf6172740d46060000", "type"=>"appli"}, "user"=>"7fbceaa661727417f55e0000"} Rendered users/_downloads.html.erb (60.7ms) Completed 200 OK in 106ms (Views: 63.1ms)
I think that I am facing a javascript problem now.
Upvotes: 2
Views: 1152
Reputation: 760
Well, finally solved my problem. I replaced in my controller
render(:partial => 'users/downloads', locals: {user: user}, :layout => false) # rendering html:(
with something like
format.js {render(users/show.js.erb)} # should render js!
Upvotes: 1
Reputation: 1371
It looks like your controller is returning an HTML response instead of a Script response. Try adding the parameter :remote => true in your link_to:
<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, :remote => true %>
and make sure that your controller has a corresponding format.js in the response block
Upvotes: 1