Rails "No route matches POST /images/1" 错误

Rails "No route matches POST /images/1" error

我查看了其他几个类似的帮助问题,但没有发现我的错误。我已经销毁、新建、创建所有工作,但 post 并显示抛出错误。同样奇怪的是,单击索引视图上的 'edit' 按钮会引发错误,但直接转到 http://localhost:3000/images/1 会给我 'show' 页面(不知道为什么它不提供编辑页面).

相关文件:

images_controller.rb

class ImagesController < ApplicationController
  def index
    @images = Image.all
  end

  def new
    @image = Image.new
  end

  def create
    @image = Image.new(image_params)

    if @image.save
        redirect_to images_path, notice: "Your image #{@image.name} has been uploaded."
    else
        render "new"
    end
  end

  def edit
    @image = Image.find(params[:id])
  end

  def destroy
    @image = Image.find(params[:id])
    @image.destroy
    redirect_to images_path, notice: "The image #{@image.name} has been removed from the database."
  end

  def show
    @image = Image.find(params[:id])
  end

  private
  def image_params
    params.require(:image).permit(:name, :attachment)
  end
end

routes.rb

Rails.application.routes.draw do    
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
 resources :images#, only: [:index, :new, :create, :update, :edit, :show, :destroy]
 root "images#index" 
end

注意:我还添加了行

get 'images/edit'

get 'images/details'

但是没有用。

index.html.erb:

<% if !flash[:notice].blank? %>
  <div class="alert alert-info">
  <%= flash[:notice] %>
  </div>
<% end %>
<br />
<%= link_to "New Image", new_image_path, class: "btn btn-primary" %>
<br />
<br />
<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>Name</th>
      <th>View Link</th>
      <th>&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <% @images.each do |image| %>
      <tr>
        <td><%= image.name %></td>
        <td><%= link_to "#{image.name}", image.attachment_url %></td>
        <td><%= button_to "Edit",  image, method: :edit, class: "btn btn-primary", confirm: "edit #{image.name}?" %></td>
        <td><%= button_to "Show",  image, method: :show, class: "btn btn-primary"%></td>
        <td><%= button_to "Delete",  image, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{image.name}?" %></td>
      </tr>
    <% end %>
  </tbody>
</table>

button_to默认会发出post请求,你需要link_to "edit"才能发出get请求。当您在浏览器中输入 http://localhost:3000/images/1 时,您正在发出获取请求,因此它可以正常工作。

link_to "Edit", edit_image_path image

检查这些链接以获得 link_to 和 button_to http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to http://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

我想没有像这样的 HTTP 方法:

method: :edit, method: :show

尝试这样做:

link_to "Edit", edit_image_path(image)
link_to "Show", image_path(image)

并从 routes.rb

中删除这一行
get 'images/edit'

resources 已经为您创建了 rout to edit 操作。可以看看http://localhost:3000/rails/info/routes