nil的未定义方法`map':NilClass,是什么原因造成的?

时间:2013-06-06 10:54:14

标签: ruby-on-rails

嗨,我正面临这个错误, 对rails来说是全新的,所以无法弄清楚导致它的原因

我的newBook.html.erb

<html>
    <head>
        <title> new Book </title>
    </head>
    <body>
        <h1><%= @hello_message %></h1>
        <h1>Add new book</h1>
        <%= form_tag :action => 'create' %>
        <p>
            <label for="book_title">Title</label>:
            <%= text_field 'book', 'title' %>
        </p>
        <p>
            <label for="book_price">Price</label>:
            <%= text_field 'book', 'price' %>
        </p>
        <p>
            <label for="book_subject">Subject</label>:
            <%= collection_select(:book,:subject_id,@subjects,:id,:name) %>
        </p>
        <p>
            <label for="book_description">Description</label>
            <br/>
            <%= text_area 'book', 'description' %>
        </p>
        <%= submit_tag "Create" %>
        <%= end_form_tag %>
        <%= link_to 'Back', {:action => 'list'} %>
    </body>
</html>

我的书模型:book.rb

class Book < ActiveRecord::Base
  attr_accessible :title, :price,:description , :created_at 
  belongs_to :subject
  validates_presence_of :title
  validates_numericality_of :price, :message=>"Error Message"
end

我的主题模型:subject.rb

class Subject < ActiveRecord::Base
  attr_accessible :name
  has_many :book

end

堆栈跟踪是:

actionpack (3.2.13) lib/action_view/helpers/form_options_helper.rb:364:in `options_from_collection_for_select'
actionpack (3.2.13) lib/action_view/helpers/form_options_helper.rb:600:in `to_collection_select_tag'
actionpack (3.2.13) lib/action_view/helpers/form_options_helper.rb:191:in `collection_select'
app/views/home/newBook.html.erb:19:in `_app_views_home_new_ook_html_erb__299261930_24178164'
actionpack (3.2.13) lib/action_view/template.rb:145:in `block in render'
activesupport (3.2.13) lib/active_support/notifications.rb:125:in `instrument'
actionpack (3.2.13) lib/action_view/template.rb:143:in `render'
# -- snipped --

4 个答案:

答案 0 :(得分:18)

<%= collection_select(:book,:subject_id,@subjects,:id,:name) %>

您的@subjects对象未定义。您需要在控制器操作中为此页面设置一些设置该变量内容的内容,例如:

@subjects = Subject.all 

查看options_from_collection_for_select的来源 - 首先要做的是对传递给它的集合进行地图调用(在您的情况下为@subjects)。

答案 1 :(得分:1)

<%= collection_select(:book,:subject_id,Subject.all,:id,:name) %>

答案 2 :(得分:0)

对于正在看这篇文章的人来说,答案对他们没有帮助;

我试图在表“部门”中链接表“位置”。

以下代码为我工作,从原始答案中汲取了灵感;

# In app/views/departments/_form.html.erb:
...
    <p>
        <%= f.label :location %><br>
        <%= f.collection_select(:location,@locations,:id,:address) %>
    </p>    
...

# In app/controllers/departments_controller.rb;

  def new
    @locations = Location.all
  ....
  end

答案 3 :(得分:0)

我最近遇到了这个问题。我已经为 new 方法(它使用 GET 调用表单页面)定义了对象,但忘记为 create 方法定义它(它使用 {{1} }),在为 POSTnew 问题定义之后得到解决。