【问题标题】:/YYYY/MM/Title-Slug URL structure with Friendly_Id Solution Chokes on #edit/YYYY/MM/Title-Slug URL 结构与 Friendly_Id 解决方案在#edit 上阻塞
【发布时间】:2015-09-18 17:52:55
【问题描述】:

根据我在解决我的original issue to implement /YYYY/MM/Slug URL structure 时在earlier question 中获得的指导,我希望能获得一些帮助来解决我在尝试编辑帖子时收到的错误:

没有路由匹配 [PATCH] "/blog/2015/09/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     '/:year/:month/: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(@post.year, @post.month, @post), 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

  def edit_post_path(post)
    "#{post.year}/#{post.month}/#{post.slug}/edit"
  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
  • 创建新帖子
  • 销毁帖子

…什么不起作用:

  • 编辑帖子(将呈现带有表单的编辑页面,但在提交更改后,您将收到上述错误 - 更改永远不会进入数据库)

我认识到此重复问题可能与此 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,最终导致窒息。想法?提前致谢!

编辑

edit.html.erb

<h1>Editing Post</h1>

<%= render 'form' %>

<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>

_form.html.erb

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
        <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_field :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

【问题讨论】:

  • 您能出示您的edit.html.erb 文件吗?我怀疑这就是问题所在。
  • 编辑了问题以包括edit.html.erb 和它使用的_form.html.erb 部分。谢谢!
  • 看起来form_for 正在生成一条“友好”路径,但您并不真正想要这样,对吗?不应该直接去PATCH /blogs/:id吗?
  • @zetetic - 这个想法是利用 friendly_id 在所需的 URL 结构中生成 slug。我对 _form 部分所做的唯一更改是删除了脚手架生成的 :slug 字段。
  • @MichalSzyndel - 感谢您的建议,因为我掌握了最佳实践,非常感谢!我以为我已经简洁地提出了这个问题,我认为最好分享每个已更改的文件(以防止有人要求添加信息),并概述我试图自我解决的所有内容。很抱歉您发现结果太长。我会努力缩短未来的问题。

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


【解决方案1】:

看起来主要问题出在助手中。返回的路径需要以斜杠开头:

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

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

如果没有斜线开头,浏览器会将它们视为相对路径,将它们附加到当前路径(这就是为什么您在提交编辑表单时以 /blog/2015/09/example-post/blog/2015/09/example-post 结尾的原因)。

您还需要确保您的 patchput 路由是一致的:

get     '/:year/:month/:id',      to: 'posts#show',   as: 'post'
patch   '/:year/:month/:id',      to: 'posts#update'
put     '/:year/:month/:id',      to: 'posts#update'
delete  '/:year/:month/:id',      to: 'posts#destroy'

最后,控制器需要包含PostsHelper 并使用其方法在createupdate 中重定向URL:

class PostsController < ApplicationController
  include PostsHelper
...
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to post_path(@post), 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(@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
...
end

【讨论】:

  • 谢谢你@neuronaut!一切都很漂亮!也感谢您花时间解释这一切 - 我不知道去掉前导斜线会告诉 Rails 这是一条相对路径。
猜你喜欢
  • 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
相关资源
最近更新 更多