【问题标题】:redirect_to in action destroy ruby on railsredirect_to 在行动中摧毁 ruby​​ on rails
【发布时间】:2014-12-31 01:57:16
【问题描述】:

我在 db/config 中有以下资源

resources :posts do

      resources :comments

    end

我的控制器内部有以下操作销毁,称为 Comment

  def destroy
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to post_path(@post)
 end

当我消除评论栏重定向到@post的url时

example /posts/1

但我不想重定向到该网址而是要重定向到

posts/1/comments 

【问题讨论】:

  • Rails 正在按照您的要求进行操作。如果你想重定向到一个帖子的 cmets,你需要post_comments_path

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2


【解决方案1】:

使用

redirect_to post_comments_path(@post)

在命令行中,如果您执行rake routes,它将显示:

       Prefix Verb    URI Pattern                                                                       Controller#Action
post_comments GET     /posts/:post_id/comments(.:format)                                                comments#index

post_comments 前缀让您知道您有两个可用的助手:post_comments_pathpost_comments_url 用于生成关联的路径或 url。

【讨论】:

  • 非常感谢马特。我真的是 Rails 的新手
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
相关资源
最近更新 更多