redirect_to with:anchor.:锚点在Show动作上丢失,但在Create上运行正常

Ada*_*dam 11 anchor redirect ruby-on-rails ruby-on-rails-4

在我的Rails论坛应用程序中,当在主题中创建新帖子时,它将重定向到topic_path,其中包含页面索引和锚点的附加参数,以便滚动到帖子.像这样:

应用程序/控制器/ posts_controller.rb

def create
  @topic = Topic.find(params[:topic_id])
  @post = @topic.posts.build(post_params.merge({user_id: current_user.id}))

  if @post.save
    flash[:success] = "Post Created"
    redirect_to topic_path(@topic, :page => @post.page, :anchor => @post.anchor) 
  else
    render 'new'
  end
end
Run Code Online (Sandbox Code Playgroud)

重定向后的URL是: http://localhost:3000/topics/1?page=3#post-1364

但是我在Posts控制器的Show动作中做同样的事情.由于我不想自己显示帖子,因此该操作只需使用页面索引和帖子锚定重定向到主题.

应用程序/控制器/ posts_controller.rb

# Post are not displayed on their own. Showing one will jump to the post inside its topic
def show
  post = Post.find(params[:id])
  redirect_to topic_path(post.topic, :page => post.page, :anchor => post.anchor)
end
Run Code Online (Sandbox Code Playgroud)

但是为帖子调用show方法后的url不包含锚点.它确实包括页面:http://localhost:3000/topics/1?page=3 我调试了show方法,post.anchor正在被正确解析.

我的终端输出显示锚由于某种原因丢失

Started GET "/posts/1364" for 127.0.0.1 at 2014-08-13 10:03:31 -0700
Processing by PostsController#show as HTML
  Parameters: {"id"=>"1364"}
  Post Load (0.5ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", "1364"]]
  Topic Load (0.2ms)  SELECT "topics".* FROM "topics" WHERE "topics"."id" = ? LIMIT 1  [["id", 1]]
  Post Load (1.3ms)  SELECT "posts".* FROM "posts" WHERE "posts"."topic_id" = ?  [["topic_id", 1]]
Redirected to http://localhost:3000/topics/1?page=3#post-1364
Completed 302 Found in 165ms (ActiveRecord: 3.7ms)


Started GET "/topics/1?page=3" for 127.0.0.1 at 2014-08-13 10:03:32 -0700
Run Code Online (Sandbox Code Playgroud)

如果它有帮助,这里是我的任何涉及帖子的路线.

    topic_posts GET    /topics/:topic_id/posts(.:format)      posts#index
                POST   /topics/:topic_id/posts(.:format)      posts#create
 new_topic_post GET    /topics/:topic_id/posts/new(.:format)  posts#new
      edit_post GET    /posts/:id/edit(.:format)              posts#edit
           post GET    /posts/:id(.:format)                   posts#show
                PATCH  /posts/:id(.:format)                   posts#update
                PUT    /posts/:id(.:format)                   posts#update
                DELETE /posts/:id(.:format)                   posts#destroy
Run Code Online (Sandbox Code Playgroud)

And*_*yev 6

检查以下问题:

URL片段和302重定向

302重定向到相对URL是有效还是无效?

  redirect_to topic_path(post.topic, :page => post.page, :anchor => post.anchor, :status => 303) 
Run Code Online (Sandbox Code Playgroud)

应该管用。