无法使用嵌套路由创建

时间:2014-09-02 19:30:12

标签: ruby-on-rails nested-routes

努力让创建在以下控制器中为我的嵌套路由工作:

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]

  before_filter :load_author

  # GET /books
  # GET /books.json
  def index
    @books = @author.books.all
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = @author.books.new
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = @auhtor.books.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to [@parent, @child], notice: 'Book was successfully created.' }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:name, :author_id)
    end

    def load_author
        @author = Author.find(params[:author_id])
    end
end

我在第29行遇到以下错误:

undefined method `books' for nil:NilClass

有什么想法吗?它正确地填充了创建视图中的author_id字段,但是当我单击“保存”时,我收到此错误。

1 个答案:

答案 0 :(得分:2)

确定在解决问题后你会大声笑出来。

您将MISSPELLED实例对象设为@auhtor@author行动的第一行应为create

@book = @author.books.new(book_params)