This is the error I get when I try to fill in the book's form: undefined method 'books' for nil:NilClass
& it highlights this line: @book = @owner.books.build(params[:book])
This is what I've done so far:
What am I missing?
Two models: owner and book
Here's the schema
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
Here are the models:
class Owner < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :owner
validates :owner_id, presence: true
end
This is in book controller:
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
EDIT
This is in the owner's controller:
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
EDIT 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
**EDIT 3 **
The method I used in book's controller in create came from this stack
The error clearly says that @owner is nil. At BooksController
you need to get the @owner object. As Owner and Books has nested association. So you need to define the routes like:
resources :owners do
resources :books
end
At BooksController
class BooksController < ApplicationController do
def create
@owner=Owner.find(params[:id])
@book = @owner.books.build(params[:book])
....
end
end
For details, closely look at Getting Started Article-Comment association example.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다