/YYYY/MM/Title-Slug URL structure with Friendly_Id

2020-03-26 07:43发布

问题:

Based on guidance I got in my earlier question in resolving my original issue to implement /YYYY/MM/Slug URL structure, I'm hoping to get some help in resolving an error I'm receiving when attempting to edit a post:

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

Here are all the files in question (working off the same very simple scaffolded blog):

$ 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 %>

In summary, here's what works:

  • /blog/index
  • /blog/2015/09/example-post
  • Creating a new post
  • Destroying a post

…What doesn't work:

  • Editing a post (the edit page with the form will render, but after submitting your changes you'll get the aforementioned error - and the changes never make it to the DB)

I recognize that this duplication problem likely lies with this edit_post_path override, but the following attempts to force the correct PATCH route have no effect:

  1. Update PATCH route to patch '/:year/:month/:id', to: 'posts#update'
  2. Name the updated PATCH route to as: 'patch' and add PATCH path override to posts_helper:

    def patch_path(post)
      "#{post.year}/#{post.month}/#{post.slug}"
    end
    
  3. Change the override to:

    def patch_path(post)
      ""
    end
    
  4. Un-name & change PATCH route to patch '', to: 'posts#update'

Looking at the posts_controller, it doesn't look like the problem is there since it's not the redirect is not the problem - and I don't see why @post.update(post_params) would be problematic:

  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

So as far as I can tell the duplication in the URL is happening prior to the PATCH action, which brings us back to the EDIT flow - it must be passing the duplication to PATCH where it winds up choking. Ideas? Thanks in advance!

EDIT

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 %>

回答1:

It looks like the primary problem is in the helper. The paths returned need to begin with a slash:

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

Without the beginning slash the browser treats them as relative paths, tacking them on to the current path (which is why you end up with /blog/2015/09/example-post/blog/2015/09/example-post when submitting the edit form).

You'll also need to make sure that your patch and put routes are consistent:

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'

And lastly the controller needs to include PostsHelper and use its methods for the redirect URLs in create and update:

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