两个模型之间的关联

association between two models

这是我在尝试填写图书表格时遇到的错误:undefined method 'books' for nil:NilClass & 它突出显示了这一行:@book = @owner.books.build(params[:book])

这是我到目前为止所做的:

我错过了什么?

两个模型:所有者和书

这是架构

create_table "books", force: :cascade do |t|
  t.string   "title"
  t.string   "isbn"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer  "owner_id"
end

add_index "books", ["owner_id"], name: "index_books_on_owner_id"

create_table "owners", force: :cascade do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.string   "email"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
 end
end

以下是模型:

class Owner < ActiveRecord::Base
   has_many :books
 end

class Book < ActiveRecord::Base
   belongs_to :owner  
  validates :owner_id, presence: true
 end

这在图书控制器中:

  def create
   @book = @owner.books.build(params[:book])
     respond_to do |format|
    if @book.save
      format.html { redirect_to @book, 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

编辑

这是在所有者的控制器中:

   def create
      @owner = Owner.new(owner_params)

     respond_to do |format|
     if @owner.save
       format.html { redirect_to @owner, notice: 'Owner was successfully created.' }
       format.json { render :show, status: :created, location: @owner }
     else
       format.html { render :new }
       format.json { render json: @owner.errors, status: :unprocessable_entity }
     end
end
end

编辑 2

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

   # Never trust parameters from the scary internet, only allow the white list through.
    def owner_params
      params.require(:owner).permit(:first_name, :last_name, :email, :title, :isbn)
     end

**编辑 3 **

我在create中book的controller中使用的方法来自这个stack

错误清楚地表明@owner 为零。在 BooksController 您需要获取 @owner 对象。由于 Owner 和 Books 具有嵌套关联。所以你需要像这样定义路由:

resources :owners do
   resources :books
end

BooksController

class BooksController < ApplicationController do 

   def create
     @owner=Owner.find(params[:id])
     @book = @owner.books.build(params[:book])
     ....
   end
end

有关详细信息,请仔细查看 Getting Started 文章-评论关联示例。