Daniel
Daniel

Reputation: 379

Rails - Associate three Models

Having three models: Datum, Author, and Book .

class Datum < ApplicationRecord
  has_many :authors
end

class Book < ApplicationRecord
 belongs_to :author
end

class Author < ApplicationRecord
 belongs_to :datum
 has_many :books, dependent: :destroy
end

For exercise purpose, I wanted to model it that Datum(more general), can have many authors, which can have books. After creating a datum object and an associated author for it, I could call nameofdatum.authors, but if I added a book to that author, it could not be recognized through nameofdatum.authors.books. Am I having wrong expectations ? (Should this be done with 'through'(an explanation of it would be much appreciated)

(Schema here if needed)

 create_table "authors", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "book_id"
    t.integer "datum_id"
    t.index ["book_id"], name: "index_authors_on_book_id"
    t.index ["datum_id"], name: "index_authors_on_datum_id"
  end



 create_table "books", force: :cascade do |t|
    t.string "name"
    t.string "book_type"
    t.integer "pages"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "author_id"
    t.index ["author_id"], name: "index_books_on_author_id"
  end



create_table "data", force: :cascade do |t|
    t.string "region"
    t.integer "budget"
    t.date "aval"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

Upvotes: 0

Views: 54

Answers (2)

Igor Drozdov
Igor Drozdov

Reputation: 15055

Should this be done with 'through'?

Yes, Datum has_many books through the authors assocition:

class Datum < ApplicationRecord
  has_many :authors
  has_many :books, through: :authors
end

And the books can be selected via:

Datum.last.books

It's actually selects books using the following query:

SELECT  "books".* FROM "books" INNER JOIN "authors" ON "authors"."id" = "books"."author_id" WHERE "authors"."datum_id" = ?

Upvotes: 1

trunglee
trunglee

Reputation: 11

If you want to add a new book through author, you have to assign an author. So you can try: nameofdatum.author.books.build ....

your codenameofdatum.authors.books, you can't use a plural(author) to add a new book. Hope to help you.

Upvotes: 0

Related Questions