/YYYY/MM/Title-Slug URL结构与Friendly_Id解决方案阻塞#new和#edit



我有一个部分解决方案,我以前的问题,这是正确显示帖子#index和帖子#show路由,但在创建一个帖子后窒息:

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

提取的源代码(第#32行左右):
30   31日,,,,,,如果@post.save
32        format.html {redirect_to post_path, notice: 'Post创建成功。'}
33岁,,,,,,,,的格式。Json {render:show, status::created, location: @post}
34岁,,,,,,其他
35       

和编辑文章:

没有路由匹配[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/文章/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 %>

总的来说,下面是工作原理:

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

…什么不工作:

  • 编辑一篇文章(带有表单的编辑页面将呈现,但在提交您的更改后,您将得到上述错误-并且更改从未使其进入DB)
  • 创建新帖子后完成重定向(前面提到)。
  • /博客/2015/指数
  • /博客/2015/09/指数

我很高兴我已经走了这么远-任何指导解决这些悬而未决的问题将是非常感激的!

编辑

感谢@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),并成功渲染编辑页面。但是这会导致补丁中断(实际上,更新没有到达DB):

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. Un-name,将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,从而导致阻塞。想法吗?

您的错误状态:

No route matches {:action=>"show", :controller=>"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.' }

在更新和创建操作更改:

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

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

相关内容

最新更新