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

时间:2014-08-13 17:25:41

标签: ruby-on-rails redirect ruby-on-rails-4 anchor

在我的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

重定向后的网址为: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

但是为帖子调用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

如果有帮助的话,以下是涉及帖子的任何路线。

    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

1 个答案:

答案 0 :(得分:5)

检查这个问题:

URL Fragment and 302 redirects

Is a 302 Redirect to relative URL valid, or invalid?

  redirect_to topic_path(post.topic, :page => post.page, :anchor => post.anchor, :status => 303) 

应该有用。