-1

这是我的路线.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%>
4

2 回答 2

0

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

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

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

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

rake routes
于 2017-05-17T09:00:04.380 回答
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%>

我希望这能帮到您。

于 2017-05-17T09:05:01.037 回答