问题
I am trying to generate a form using erb in a rails application. I am continually getting the NoMethodError for line #3 of my .html.erb file. Below is the migration, the controller, the model, and the .html.erb
The error is "undefined method `class_projects_path'"
Migration:
class CreateClassProjects < ActiveRecord::Migration
def change
create_table :class_projects do |t|
t.string :name
t.text :description
t.text :summary
t.text :github
t.text :other_url
t.timestamps
end
end
end
Model:
class ClassProject < ActiveRecord::Base
attr_accessible :description, :github, :name, :other_url, :summary
end
Controller:
class ClassProjectsController < ApplicationController
def new
@class_project = ClassProject.new
end
end
new.html.erb:
<h1>New Class Project</h1>
<%= form_for @class_project do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :summary %>
<%= f.text_field :summary %>
<%= f.label :github %>
<%= f.text_field :github %>
<%= f.label :other_url %>
<%= f.text_field :other_url %>
<% end %>
Route for good measure:
get 'new_project' => 'class_projects#new', :as => 'new'
Thanks for any help, inb4 learn to code nub, use the search function nub, etcetera.
回答1:
You'll need to use the following:
#config/routes.rb
resources :class_projects
This means you'll be able to use the following:
#app/controllers/class_projects_controller.rb
class ClassProjectsController < ApplicationController
def new
@class_project = ClassProject.new
end
end
#app/views/class_projects/new.html.erb
<%= form_for @class_project do |f| %>
...
<% end %>
--
Routes
The problem you have is that you have not declared a full compliment of routes for your class_projects objects. Rails runs a resourceful (object orientated) routing system, meaning that if you invoke the resources directive, you'll be provided with a full CRUD routing structure:
This means that if you use a helper such as form_for (which builds routes based on your provided object), you'll have to have this CRUD compliment of routes set up.
Defining your routes file as above will give you the ability to call the form_for helper with impunity (and no extra arguments)
回答2:
you didn't define a resources route, so your form needs an extra config
<%= form_for @class_project, url: new_path do |f| %
来源:https://stackoverflow.com/questions/25734405/rails-form-for-nomethoderror