association between two models

user273072545345

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

Masudul

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How to create association one to many and many to one between two entities in gorm?

분류에서Dev

Entity Framework - Oracle 11 - Insert Association/Link record between two tables

분류에서Dev

Forms that comprise of two models

분류에서Dev

Rails Association - Simple Form with separate models and forms in one view

분류에서Dev

Checking for relationships between related models?

분류에서Dev

Database association, Case model has two People

분류에서Dev

Two Association Label Elements in Simple Form

분류에서Dev

Rails How display with two database association

분류에서Dev

Show two models (Images and Treatments) in one table

분류에서Dev

Use the same _Id in two models with backbone and mongodb

분류에서Dev

Passing two models to Controller using Ajax BeginForm()

분류에서Dev

xcorr between two matrices

분류에서Dev

show records from two different models using pagination

분류에서Dev

Is it possible to host two different Odata models in a Web API service

분류에서Dev

Yii multiple relations between different models in different modules

분류에서Dev

Gap Between two two dates of different cells

분류에서Dev

Every two elements mean between these two element

분류에서Dev

QGraphicsPathItem between two movable QGraphicsRectItem

분류에서Dev

Angle between two vectors matlab

분류에서Dev

mirroring a pane between two windows

분류에서Dev

Exponential probability between two numbers?

분류에서Dev

Difference in years between two dates

분류에서Dev

Checking if time is between two intervals

분류에서Dev

Distance Between Two Geo Coordinates

분류에서Dev

Center div between two divs

분류에서Dev

Many-to-Many Relationship between two tables in two different databases

분류에서Dev

DNS server selection between two LAN interfaces

분류에서Dev

Transitioning ownership of a file between two deb packages

분류에서Dev

Matching ID between two pandas series

Related 관련 기사

  1. 1

    How to create association one to many and many to one between two entities in gorm?

  2. 2

    Entity Framework - Oracle 11 - Insert Association/Link record between two tables

  3. 3

    Forms that comprise of two models

  4. 4

    Rails Association - Simple Form with separate models and forms in one view

  5. 5

    Checking for relationships between related models?

  6. 6

    Database association, Case model has two People

  7. 7

    Two Association Label Elements in Simple Form

  8. 8

    Rails How display with two database association

  9. 9

    Show two models (Images and Treatments) in one table

  10. 10

    Use the same _Id in two models with backbone and mongodb

  11. 11

    Passing two models to Controller using Ajax BeginForm()

  12. 12

    xcorr between two matrices

  13. 13

    show records from two different models using pagination

  14. 14

    Is it possible to host two different Odata models in a Web API service

  15. 15

    Yii multiple relations between different models in different modules

  16. 16

    Gap Between two two dates of different cells

  17. 17

    Every two elements mean between these two element

  18. 18

    QGraphicsPathItem between two movable QGraphicsRectItem

  19. 19

    Angle between two vectors matlab

  20. 20

    mirroring a pane between two windows

  21. 21

    Exponential probability between two numbers?

  22. 22

    Difference in years between two dates

  23. 23

    Checking if time is between two intervals

  24. 24

    Distance Between Two Geo Coordinates

  25. 25

    Center div between two divs

  26. 26

    Many-to-Many Relationship between two tables in two different databases

  27. 27

    DNS server selection between two LAN interfaces

  28. 28

    Transitioning ownership of a file between two deb packages

  29. 29

    Matching ID between two pandas series

뜨겁다태그

보관