gpt4 book ai didi

ruby-on-rails - redirect_to 为 :anchor. :anchor 在 Show 操作中丢失,但在 Create 操作中工作正常

转载 作者:行者123 更新时间:2023-12-02 07:20:39 25 4
gpt4 key购买 nike

在我的 Rails 论坛应用程序中,当在主题中创建新帖子时,它将重定向到 topic_path,并带有页面索引和 anchor 的附加参数,以便滚动到帖子。就像这样:

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

但我在帖子 Controller 的显示操作中做了同样的事情。由于我不想单独显示帖子,因此该操作只需重定向到带有页面索引和帖子 anchor 的主题。

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 不包含 anchor 。但它确实包含该页面:http://localhost:3000/topics/1?page=3我调试了 show 方法,并且 post.anchor 已正确解析。

我的终端输出显示 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

最佳答案

检查这个问题:

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) 

应该可以。

关于ruby-on-rails - redirect_to 为 :anchor. :anchor 在 Show 操作中丢失,但在 Create 操作中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com