本文介绍了如何将锚添加到redirect_to:back的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客应用程序,该应用程序的帖子可以通过posts控制器中的vote动作获得投票.因为我同时允许在索引视图和显示视图中投票,所以投票后我redirect_to :back,如下所示.

I have a blogging application that has posts that can receive votes through a vote action in the posts controller.Because I allow voting in both the index and show views, I redirect_to :back after a vote is made, as below.

def vote
  # voting logic goes here
  redirect_to :back
end

这会将我重定向到正确的页面,但我想重定向到页面中的特定帖子.为此,我在帖子的部分div中添加了一个可识别的锚点.

This redirects me to the correct page, but I want to redirect to the specific post within the page. To do this, I added an identifying anchor to my post partial div.

<div id="post_<%= post.id %>">
  <%= post.content %>
</div>

如何在redirect_to :back中引用此内容?我尝试了以下操作,但这不起作用.

How can I reference this in my redirect_to :back? I tried the below, which doesn't work.

# this doesn't work!
redirect_to :back, anchor: "post_#{@post.id}"

或者,如果要在显示视图和索引视图中使用if子句,该怎么做?我尝试了下面的方法,该方法返回undefined method 'current_page' for VocabsController.

Alternatively, if I were to use an if clause for the show and index views, how do I do that? I tried the below, which returns undefined method 'current_page' for VocabsController.

#this doesn't work!
if current_page?(posts_path)
  redirect_to posts_path(anchor: "post_#{@post.id}"
else
  redirect_to @post
end

推荐答案

我最终改用了Javascript.

I ended up using Javascript instead.

posts_controller.rb

posts_controller.rb

def vote
  @post = Post.find(params[:id])
  #voting logic
  respond_to do |format|
    format.html { redirect_to :back }
    format.js
  end
end

posts/_post.html.erb

posts/_post.html.erb

<div class="post_partial" id="post_<%= post.id %>">
  <%= post.content %>
  <div id="vote_button_<%= post.id %>">
    <%= link_to "up", vote_path, method: "post", remote: true %>
  </div>
</div>

posts/vote.js.erb

posts/vote.js.erb

$('#post_<%= @post.id %>').html('<%= j render @post %>');

这篇关于如何将锚添加到redirect_to:back的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:17