Routing Error - No route matches [POST] for new

折月煮酒 提交于 2019-12-22 12:21:11

问题


I'm getting an error with routes and I can't find where is the problem, I'm creating a simple CRUD and get this trouble with the create method.

Error

No route matches [POST] "/usuarios/new"

Controller

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 %>

回答1:


As Flexoid has pointed out, you probably haven't add the new method in the controller.

So, put this

def new
  @usuario = Usuario.new
end

EDIT

You have to pay more attention.

Take a look:

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



回答2:


Change

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

to

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



回答3:


Seems like you forgot about configuring of the Rails Router.

Try to add this to your config/routes.rb file:

resources :usuarios

For the reference you can read rails guide Rails Routing from the Outside In.



来源:https://stackoverflow.com/questions/10863673/routing-error-no-route-matches-post-for-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!