-1

我对 Ruby 非常陌生,大约 4 周前才开始学习。我现在只是在建造一些非常小的东西。一个包含一些字段的表单,用于存储有关书名的数据输入,然后将其吐出到下面的列表中,到目前为止,这就是我得到的:

books_controller.rb

    class BooksController < ApplicationController
  def add
    @book_name = params[:book_name]
  end

  def sign_in
        @book_name = params[:book_name]
    unless @book_name.blank?
        @book = Book.create({:book_name => @book_name})
    end
        @books = Book.all
  end
end

这是创建控制器的地方。我认为非常直接。

这是这里的数据库创建者:

class CreateBooks < ActiveRecord::Migration
  def change
    create_table :books do |t|
      t.string :book_name
      t.timestamps
    end
  end
end

然后我们有 app/models/book.rb:

class Book < ActiveRecord::Base
  attr_accessible :book_name
end

然后我有一个添加模板,其中添加了书名并创建了列表(这是我收到错误的页面)

<p>Find me in app/views/books/add.html.erb</p>

<h2>Recent book: <%= @book_name %> and the Author is: <%= @book_author %></h2>
<%= form_tag :action => 'add' do %>
<p>Book name: <%= text_field_tag 'book_name', @book_name %></p>
<%= submit_tag 'Add Book' %>
<% end %>

<p>Book list:</p>
<ul>
<% @books.each do |book| %>
<li><%= book.book_name %></li>
<% end %>
</ul>
<hr>
<%= debug(params) %>
<%= debug(assigns) %>

有人会碰巧知道我为什么会收到此错误吗,我将在下面显示完整的错误:

书籍中的 NoMethodError #add undefined method `each' for nil:NilClass

任何帮助都会很好。

干杯,马克

4

1 回答 1

4

Book#add is calling an undefined method. #add is defined in BooksController, not Book.

Unfortunately, this is only one of several issues. Your code suggests an incomplete understanding of how Rails works, which is not atypical of someone just starting out.

I suggest you focus your Rails studies on:

  • the HTTP request/response cycle
  • instance variables, especially lifespan and scope in controllers
  • CRUD methods (a basic Rails convention)
  • MVC architecture and the relationship between controllers and models
于 2013-01-20T12:50:00.673 回答