错误:书籍中的 NoMethodError#create
显示 C:/work/Library/app/views/books/new.html.erb 其中第 21 行提出:
nil:NilClass 的未定义方法 `map' 提取的源代码(第 21 行附近):
18: <td><%= f.text_area :description %></td></tr>
19:
20: <tr><td><b><%= f.label 'Subject' %></b></td>
21: <td><%= f.collection_select(:subject_id,@subjects,:id,:name) %></td></tr>
22:
23: <tr><td><%= f.submit 'Save' %></td></tr>
控制器:类 BooksController < ApplicationController
before_filter :self_load, :only=>[:edit,:show,:update,:destroy]
def index
@books=Book.where(:subject_id=>params[:id])
end
def new
@book=Book.new
@subjects=Subject.all
end
def create
@book=Book.new(params[:book])
if @book.save
redirect_to root_url, :notice=>'New Book has been added'
else
render :action=>'new'
end
end
def edit
end
def update
if @book.update_attributes(params[:book])
redirect_to books_path, :notice=>'Book has been updated'
else
render :action=>'edit'
end
end
def show
end
def destroy
@book.destroy
redirect_to root_url
end
def self_load
@book=Book.find(params[:id])
end
end
class SubjectsController < ApplicationController
before_filter :self_load, :only=>[:edit,:show,:update,:destroy]
def index
@subjects=Subject.all
@books=Book.all
end
def new
@subject=Subject.new
end
def create
@subject=Subject.new(params[:subject])
if @subject.save
redirect_to root_url, :notice=>'New subject has been added'
else
render :action=>'new'
end
end
def edit
end
def update
if @subject.update_attributes(params[:subject])
redirect_to root_url, :notice=>'Subject has been updated'
else
render :action=>'edit'
end
end
def show
end
def destroy
@subject.destroy
redirect_to root_url
end
def self_load
@subject=Subject.find(params[:id])
end
end
模型:类 Book < ActiveRecord::Base
belongs_to :subject
attr_accessible :title, :description, :subject_id
validates_presence_of :title,:description
validates_uniqueness_of :title
validates_length_of :title, :in=>3..20
validates_length_of :description, :minimum=>5
end
class Subject < ActiveRecord::Base
has_many :books, :dependent=> :destroy
attr_accessible :name
validates_presence_of :name
validates_uniqueness_of :name
validates_length_of :name, :in=>3..10
end
看法:
添加新书
<%= form_for(@book) 做 |f| %> <% if @book.errors.any? %>
<% @book.errors.full_messages.each 做 |msg| %>
- <%= 消息 %>
<% 结束 %>
<% 结束 %>
<table>
<tr><td><b><%= f.label 'Title' %></b></td>
<td><%= f.text_field :title %></td></tr>
<tr><td><b><%= f.label 'Description' %></b></td>
<td><%= f.text_area :description %></td></tr>
<tr><td><b><%= f.label 'Subject' %></b></td>
<td><%= f.collection_select(:subject_id,@subjects,:id,:name) %></td></tr>
<tr><td><%= f.submit 'Save' %></td></tr>
</table>
<% end %>
<%= link_to 'Back', root_url %>
当我试图添加一本新书并且我将标题和描述保持为空并尝试保存时,我遇到了未定义的方法映射错误..如果我从我的视图源中删除 collection_select 然后我尝试添加一本新书并保留描述和标题为空并尝试保存它,它显示标题和描述不应该为空......当我的视图源中有collection_select时,如果我填写标题和描述并尝试保存它......它正在工作中