没有路线匹配[POST]" / additem"试图创建一个crud项目

时间:2017-05-17 08:54:33

标签: ruby-on-rails ruby-on-rails-5.1

这是我的routes.rb

Rails.application.routes.draw do
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'maincontroller#mainview', as: 'mainview'


  get 'additem' => 'maincontroller#additem', as:  'additem'

  resources :maincontroller
end

这是我的控制器

class MaincontrollerController < ApplicationController

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

  def additem
    @post = Post.new(post_params)
    @post.save
    redirect_to @post
  end

  private 

  def post_params
    params.require(:post).permit(:item_name, :item_desc)
  end
end

这是我的additem.html.erb

<h1>Item</h1>
<%= form_for :post, url: additem_path do |f| %>
  <p>
    <%= f.label :Item_Name %><br>
    <%= f.text_field(:Item_Name, {:class => 'form-control'}) %>
  </p>
  <p>
    <%= f.label :Item_Description %><br>   
    <%= f.text_area(:item_desc, {:class => 'form-control'}) %>
  </p>
  <p>
    <%= f.submit({:class => 'btn btn-primary'})%>
  </p>
<%end%>

2 个答案:

答案 0 :(得分:0)

原因是提交表单时的默认方法是POST

因此,您只需将HTTP动词更改为post

即可
post 'additem' => 'maincontroller#additem', as:  'additem'

您可以通过以下方式检查路线:

rake routes

答案 1 :(得分:0)

你可以这样做。

在路线

Rails.application.routes.draw do
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'maincontroller#mainview', as: 'mainview'


  get 'new_item' => 'maincontroller#new_item', as:  'new_item'
  post 'add_item' => 'maincontroller#add_item', as:  'add_item'

  resources :maincontroller
end
控制器中的

class MaincontrollerController < ApplicationController

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

  def new_item
   @post = Post.new(post_params)
  end

  def add_item
    @post = Post.new(post_params)
    @post.save
    redirect_to @post
  end

  private 

  def post_params
    params.require(:post).permit(:item_name, :item_desc)
  end
end
在您的视图中

<h1>Item</h1>
<%= form_for :post, url: add_item_path do |f| %>
  <p>
    <%= f.label :item_Name %><br>
    <%= f.text_field(:item_name, {:class => 'form-control'}) %>
  </p>
  <p>
    <%= f.label :item_description %><br>   
    <%= f.text_area(:item_desc, {:class => 'form-control'}) %>
  </p>
  <p>
    <%= f.submit({:class => 'btn btn-primary'})%>
  </p>
<%end%>

我希望这会对你有所帮助。