两个模型之间的关联

时间:2015-01-14 03:36:50

标签: ruby-on-rails associations model-associations

这是我在尝试填写图书表格时遇到的错误: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 **

我在创建的书籍控制器中使用的方法来自此stack

1 个答案:

答案 0 :(得分:0)

错误清楚地表明@owner是零。在BooksController,您需要获取@owner对象。由于所有者和书籍已嵌套关联。所以你需要定义如下路线:

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文章评论关联示例。