路由错误 - 没有路由匹配[POST] for new

时间:2012-06-02 15:40:54

标签: ruby-on-rails model-view-controller

我收到路由错误,我找不到问题所在,我正在创建一个简单的CRUD并使用create方法遇到麻烦。

错误

  

没有路线匹配[POST]“/ usuarios / new”

控制器

def new
  @usuario = Usuarios.new
end 

def create
  @usuario = Usuarios.new(params[:usuario])

  if @usuario.save
    redirect_to usuario_path, :notice => "Cadastrado realizado com sucesso!"
  else
    render "new"
  end
end

new.html.erb

<h1>Add new user</h1>

<%= form_for (:usuario) do |f| %>

<p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
</p>
<p>
    <%= f.label :idade %><br />
    <%= f.text_field :idade %>
</p>
<p>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
</p>

<p>
    <%= f.submit "send" %>
</p>

<% end %>

3 个答案:

答案 0 :(得分:2)

正如Flexoid所指出的那样,你可能还没有在控制器中添加new方法。

所以,把这个

def new
  @usuario = Usuario.new
end

修改

你必须多加注意。

看看:

def new
  @usuario = Usuario.new # not Usuarios.new, that's wrong.
end  

def create
    @usuario = Usuario.new(params[:usuario]) # not usuarios, first letter should be capital

    if @usuario.save
        redirect_to usuarios_path, :notice => "Cadastrado realizado com sucesso!" # usuario_path requires an id parameter like `usuario_path(@usuario)` or you could redirect to the `index` with `usuarios_path` 
    else
        render "new"
    end
end

答案 1 :(得分:1)

更改

<%= form_for (:usuario) do |f| %>

<%= form_for (@usuario) do |f| %>

答案 2 :(得分:0)

好像忘了配置Rails路由器。

尝试将其添加到您的config/routes.rb文件中:

resources :usuarios

作为参考,您可以阅读导轨Rails Routing from the Outside In