Routing Error - No route matches [POST] for new

2019-05-29 01:57发布

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

3条回答
男人必须洒脱
2楼-- · 2019-05-29 02:22

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
查看更多
迷人小祖宗
3楼-- · 2019-05-29 02:33

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.

查看更多
够拽才男人
4楼-- · 2019-05-29 02:44

Change

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

to

<%= form_for (@usuario) do |f| %>
查看更多
登录 后发表回答