Rails 路由,NoMethodError

Rails routing, NoMethodError

我正在使用 Rails 3.2 和 Ruby 4。当我浏览到 http://localhost:3000/account/new 时出现错误:

NoMethodError in Accounts#new
Showing D:/row/dev/basic/app/views/accounts/_form_account.html.erb where line #1 raised:
undefined method `accounts_path' for #<#<Class:0x42c8040>:0x6daa960>
Extracted source (around line #1):
1: <%= form_for(@account) do |f| %>
2: 
3:   <div>
4:    <%= f.label :username %><br>

我使用 rails generate controller Controllernames index show new edit delete 创建了帐户视图。我也运行rails generate model account。 根据我正在学习的在线 Rails 课程,这应该在 routes.rb:

中创建

编辑:我使用了 rails generate model accounts,所以在末尾添加了 s。

  resources :accounts
  get 'accounts/:id/delete' => 'accounts#delete', :as => :accounts_delete

但是,这不是在 routes.rb 中创建的。我的 routes.rb 经过一些编辑后是:

Basismysql::Application.routes.draw do

  # Public pages
  get '/page1' => 'pages#page1'
  get '/page2' => 'pages#page2'
  get '/page3' => 'pages#page3'

  get "/account/index" => 'accounts#index'
  get "/account/show" => 'accounts#show'
  get "/account/new" => 'accounts#new'
  get "/account/edit" => 'accounts#edit'
  get "/account/delete" => 'accounts#delete'
  get 'account/:id/delete' => 'accounts#delete', :as => :accounts_delete

  devise_for :users
  root :to => 'pages#index'
end

New.html.erb 是:

<div class="container">
  <h1>Accounts#new</h1>
  <p>Find me in app/views/accounts/new.html.erb</p>
</div>

<div class="container">
  <%= render "form_account" %>
</div>

而_form_account.html.erb是:

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

  <div>
   <%= f.label :username %><br>
   <%= f.text_field :username %>
  </div>
  <div>
   <%= f.label :firstname %><br>
   <%= f.text_field :firstname %>
  </div>
  <div>
   <%= f.label :lastname %><br>
   <%= f.text_field :lastname %>
  </div>
  <div>
    <%= f.label :organisation %>
    <%= f.text_field :organisation %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

部分账户控制人是:

  def new
    @account = Account.new
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      redirect_to(:action => 'index')
    else
      render('new')
    end
  end

private
    def account_params
    params.require(:account).permit(:username, :firstname, :lastname, :organisation)
end

除了:

resources :accounts

您可能需要:

resource :account

您已通过将路由零碎添加到路由文件来启动它,但其中一些需要 PUTs 或 POSTs 或 DELETEs。 resource :account 是一个更简单的快捷方式(正确)。

get "/account/index" => 'accounts#index'
get "/account/show" => 'accounts#show'
get "/account/new" => 'accounts#new'
get "/account/edit" => 'accounts#edit'
get "/account/delete" => 'accounts#delete'
get 'account/:id/delete' => 'accounts#delete', :as => :accounts_delete

这不是你应该创建路由的方式,它们都是未命名的(除了最后一个),非restful并且都是get,将其替换为

resources :accounts

你的错误就会消失

这个有效

rails generate controller accounts index show new edit destroy

注意:生成控制器时必须使用accounts而不是account

rails generate model account

注意:您的账户必须是单数

在routes.rb

map.resources :accounts /or
resources :accounts

取决于 rails

的版本