我正在与 acts_as_votable 一起工作.
所以我的路线是这样的:
resources :git do
member do
get :like
get :unlike
end
end
我没有创建文件
like.html.erb
& unlike.html.erb
因为我不需要 View 。我喜欢的 Action :
def like
@git = Git.find(params[:id])
@git.liked_by current_user
redirect_to :back
end
我的问题是,
Git
索引文件有一个 looooong 列表,如果有人“喜欢”它,页面会从重定向刷新,用户失去了他的滚动位置。我怎样才能阻止重定向?只做没什么 ?
我的看法:
<span><i class="fa fa-thumbs-up"></i> <%= link_to "Like", like_git_path(git) %></span>
<div class="b2-widget-count" style="display: inline-block">
<i></i><u></u><div class="b2-widget-val"><%= git.likes.size %></div>
</div>
最佳答案
最好的方式是发送head :no_content
或 render nothing: true
.由于第二个 jquery 的问题,我推荐第一个。
def like
@git = Git.find(params[:id])
@git.liked_by current_user
render text: @git.likes.size
end
将您的路由更改为 POST。
然后,确保您有
gem jquery-rails
Gemfile 中的一行。将这两行添加到您的
application.js
的顶部文件。//= require jquery
//= require jquery_ujs
将此行添加到
application.js
的底部文件:$(document).ready(function(){
$('.like-button, .unlike-button').click(function(e){
e.preventDefault();
url = $(e.currentTarget).attr('href');
$.post(url).done(function(data){
$(e.currentTarget).closest('.b2-widget-val').html(data);
});
});
});
将相应的类(
like-button, unlike-button
)添加到您的 link_to
helper 。
关于ruby-on-rails - 如何重定向到 "nothing",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123422/