【问题标题】:/YYYY/MM/Title-Slug URL structure with Friendly_Id Solution Chokes on #new and #edit/YYYY/MM/Title-Slug URL 结构,带有 Friendly_Id 解决方案阻塞 #new 和 #edit
【发布时间】:2015-09-18 04:45:51
【问题描述】:

我的previous issue 有一个部分解决方案,它可以正确显示帖子#index 和帖子#show 路线,但在创建帖子后会窒息:

PostsController#create 中的 ActionController::UrlGenerationError
没有路线匹配 {:action=>"show", :controller=>"posts"} 缺少必需的键:[:id, :month, :year]

提取的源代码(第 32 行附近):
30    respond_to do |格式|
31      如果@post.save
32        format.html { redirect_to post_path, notice: '帖子已成功创建。' }
33        format.json { 渲染:显示,状态::创建,位置:@post }
34      其他
35        format.html { 渲染:新 }

…编辑帖子:

没有路由匹配 [PATCH] "/blog/example-post/blog/2015/09/example-post"

这里是所有有问题的文件(在同一个非常简单的脚手架博客上工作):

$ rails new blog
[...]
$ cd blog
# (Add friendly_id to Gemfile & install)
$ rails generate friendly_id
$ rails generate scaffold post title content slug:string:uniq
[...]
$ rake db:migrate

routes.rb

Rails.application.routes.draw do
  scope 'blog' do
    get     '',                   to: 'posts#index',  as: 'posts'
    post    '',                   to: 'posts#create'
    get     '/new',               to: 'posts#new',    as: 'new_post'
    get     '/:id/edit',          to: 'posts#edit',   as: 'edit_post'
    get     '/:year/:month/:id',  to: 'posts#show',   as: 'post'
    patch   '/:id',               to: 'posts#update'
    put     '/:id',               to: 'posts#update'
    delete  '/:year/:month/:id',  to: 'posts#destroy'
  end
end

post.rb

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged

  def year
    created_at.localtime.strftime("%Y")
  end

  def month
    created_at.localtime.strftime("%m")
  end
end

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all
  end

  def show
    @post = Post.friendly.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def edit
    @post = Post.friendly.find(params[:id])
  end

  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to post_path, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to post_path, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.friendly.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :content, :slug)
    end
  end
end

posts_helper.rb

module PostsHelper

  def post_path(post)
    "blog/#{post.year}/#{post.month}/#{post.slug}"
  end

end

app/views/posts/index.html.erb

<p id="notice"><%= notice %></p>

<h1>Listing Posts</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Content</th>
      <th>Slug</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
  <% @posts.each do |post| %>
    <tr>
      <td><%= post.title %></td>
      <td><%= post.content %></td>
      <td><%= post.slug %></td>
      <td><%= link_to 'Show', post_path(post) %></td>
      <td><%= link_to 'Edit', edit_post_path(post) %></td>
      <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Post', new_post_path %>

总之,以下是有效的方法:

  • /博客/索引
  • /blog/2015/09/example-post
  • 创建一个新帖子(直到它应该重定向到帖子的点#show 当你得到上面提到的 UrlGenerationError 时)
    • 也就是说,新帖子已添加到数据库中,因此如果您返回 /index,新帖子将可见
  • 销毁帖子

…什么不起作用:

  • 编辑帖子(将呈现带有表单的编辑页面,但在提交更改后,您将收到上述错误 - 更改永远不会进入数据库)
  • 在创建新帖子后完成重定向(前面提到过)。
  • /blog/2015/index
  • /blog/2015/09/index

我很高兴我能走到这一步 - 任何解决这些悬而未决问题的指导将不胜感激!

编辑

感谢@brad-werth,帖子创建已通过以下更改得到修复:

posts_controller.rb

def create
  @post = Post.new(post_params)

  respond_to do |format|
    if @post.save
      format.html { redirect_to post_path(@post.year, @post.month, @post), notice: 'Post was successfully created.' }

我还尝试通过以下方式解决帖子编辑问题:

将编辑路由更改为get '/:year/:month/:id/edit', to: 'posts#edit', as: 'edit_post',并将以下覆盖添加到posts_helper.rb 以防止索引页面中断:

  def edit_post_path(post)
    "#{post.year}/#{post.month}/#{post.slug}/edit"
  end

现在,来自索引页面的“编辑”链接将转到正确的 URL(/blog/2015/09/example-post/edit - 它曾经转到 /blog/example-post/edit)并成功呈现编辑页面。但这会导致 PATCH 中断(实际上,更新不会进入数据库):

No route matches [PATCH] "/blog/2015/09/example-post/blog/2015/09/example-post"

我认识到此重复问题可能与此 edit_post_path 覆盖有关,但以下强制正确 PATCH 路由的尝试无效:

  1. 将 PATCH 路由更新为patch '/:year/:month/:id', to: 'posts#update'
  2. 将更新后的 PATCH 路由命名为 as: 'patch',并将 PATCH 路径覆盖添加到 posts_helper:

    def patch_path(post)
      "#{post.year}/#{post.month}/#{post.slug}"
    end
    
  3. 将覆盖更改为:

    def patch_path(post)
      ""
    end
    
  4. 取消命名并将 PATCH 路由更改为 patch '', to: 'posts#update'

查看posts_controller,它看起来不存在问题,因为它不是重定向不是问题 - 我不明白为什么@post.update(post_params) 会有问题:

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

据我所知,URL 中的重复是在 PATCH 操作之前发生的,这使我们回到了 EDIT 流程 - 它必须将重复传递给 PATCH,最终导致窒息。想法?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-routing


    【解决方案1】:

    您的错误状态:

    No route matches {:action=&gt;"show", :controller=&gt;"posts"} missing required keys: [:id, :month, :year]

    正如您从失败的行中看到的那样,format.html { redirect_to post_path, notice: 'Post was successfully created.' },您正在调用post_path,没有任何参数。

    您的路线 get '/:year/:month/:id', to: 'posts#show', as: 'post' 需要年份、月份和 ID。这与您上面的错误消息相吻合。

    要修复,只需提供缺少的参数,如下所示:

    format.html { redirect_to post_path(@post.year, @post.month, @post), notice: 'Post was successfully created.' }

    【讨论】:

    • 我刚刚注意到您有一个名为 post_path 的助手。这可能会覆盖您的路线,可能是故意的。你需要拉它,或者像post_path(@post) 这样称呼它。为了可维护性,定义与路由助手重叠的方法可能不是一个好计划。
    • 您的补丁错误是相同的基本内容,请注意您的路线只需要 id,而不是其他所有内容。
    • 感谢@brad-werth 的建议。将缺少的参数传递到“创建”重定向中有效。不幸的是,“更新”仍然因相同的更改而失败。
    • 至于拉取路由覆盖,据我所知,这是使 /YYYY/MM/slug URL 结构正常工作的唯一方法。如果您知道一种更好的可维护性替代方法,我很乐意采用这种方法。
    • @BrianM。我解决了 cmets 中的更新位。作为一个单独的问题真的会更好,但我认为你有足够的信息来解决这个问题。我宁愿帮助你学习,也不愿用勺子喂你一个解决方案。查看您要定位的路线,它只有 id 参数。您要么需要构建它,要么调整命名路由参数...
    【解决方案2】:

    在更新和创建操作更改中:

    format.html { redirect_to post_path, notice: 'Post was successfully ...' }
    

    format.html { redirect_to @post, notice: 'Post was successfully ...' }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多