使用 :anchor 重定向到。 :anchor 在 Show 操作中丢失,但在 Create 上工作正常
Posted
技术标签:
【中文标题】使用 :anchor 重定向到。 :anchor 在 Show 操作中丢失,但在 Create 上工作正常【英文标题】:redirect_to with :anchor. The :anchor gets lost on the Show action but works fine on Create 【发布时间】:2014-10-07 04:27:21 【问题描述】:在我的 Rails 论坛应用程序中,当在主题中创建新帖子时,它将重定向到 topic_path,并带有页面索引和锚点的附加参数,以便滚动到帖子。像这样:
app/controllers/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
重定向后的url为:http://localhost:3000/topics/1?page=3#post-1364
但是我在 Posts 控制器的 Show 动作中做同样的事情。由于我不想单独显示帖子,因此该操作只需重定向到带有页面索引和帖子锚点的主题。
app/controllers/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】:检查以下问题:
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)
应该可以。
【讨论】:
以上是关于使用 :anchor 重定向到。 :anchor 在 Show 操作中丢失,但在 Create 上工作正常的主要内容,如果未能解决你的问题,请参考以下文章
anchor_based-anchor_free object detectors