ruby 未定义的方法`users_path'

ttp71kqs  于 9个月前  发布在  Ruby
关注(0)|答案(7)|浏览(103)
<%= form_for @user1 do |f| %>

    Username: <%= f.text_field :username %>      <br />
    Password: <%= f.password_field :password %>  <br />.
    Email:    <%= f.email_field :email %> <br />

    <%= submit_tag "Add" %>

<% end %>

我是ruby新手,我正在尝试创建简单的程序,但我有这个错误,我找不到原因。我有这个错误

undefined method `users_path' for #<#<Class:0x000000020576f0>:0x0000000335d5d8>

解决的办法是什么?

class UserController < ApplicationController
  def add
    @user1 = User.new
    respond_to do |format|
      format.html
      format.json {render :json => @user1}
    end
  end
bjp0bcyl

bjp0bcyl1#

您是否在config/routes.rb中定义了routes

Rails.application.routes.draw do
  resources :users
  # ...
end
zpgglvta

zpgglvta2#

在我的config/routes.rb中,我错误地使用了user(单数):

resources :user

必须是users(复数):

resources :users
1yjd4xko

1yjd4xko3#

如果运行rake routes命令,您会发现在第一列中没有users_path的条目。这意味着您没有为提交表单时将调用的操作定义路由。
如果你想使用资源,那么只需添加:

resources: users

如果你想为users#new操作使用不同的URL(route name),那么添加

resources: users, except: [:new]

在routes.rb文件中users#new的路由下面。
而且,如果你不想去资源的方式,然后添加一个新的路线:

post 'users', to: 'users#create'
kkbh8khc

kkbh8khc4#

config/routes.rb文件中添加:

resources :users, except: [:new]
8ehkhllq

8ehkhllq5#

在类UserController中,用途:

route: get /signup, to: 'user#new'
.
.
resources :users

其中“:users“是复数,因为您将注册多个用户。

kgqe7b3p

kgqe7b3p6#

当我们有一个表单,当我们按下提交按钮时,Rails不知道在哪里提交表单时,就会发生这种情况。为此,我们需要去路由,并确保我们有resources:users

Rails.application.routes.draw do

#all the other resources and routes

resources :users

end

在另一个答案中,我看到

resources :users, except[:new]

只有当我们已经在路由中引入了新操作时才使用此操作:

resources :posts

get 'signup', to: 'users#new 

resources :users, except[:new]
ki1q1bka

ki1q1bka7#

根据您的UserController,您应该已经在config/routes.rb文件中有一个类似于以下内容的路由:

get 'users', to: 'user/#add'

在本例中,Rails将查找postusers-route。所以你也需要在routes.rb文件中定义它:

post 'users', to: 'user/#create'

要合并组合这两个路由,只需将以下内容添加到路由文件中:

resources: users

这将自动生成所有用户相关的路线。您可以通过在终端中键入以下内容来查看:

rails routes

相关问题