【发布时间】:2018-10-15 23:07:27
【问题描述】:
拥有三个模型:基准、作者和书籍。
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
出于练习的目的,我想将它建模为 Datum(更一般),可以有很多作者,可以有书籍。 在为它创建了一个基准对象和一个关联的作者之后,我可以调用 nameofdatum.authors,但是如果我给那个作者添加了一本书,它就无法通过 nameofdatum.authors.books 来识别。我有错误的期望吗? (是否应该使用“通过”来完成(非常感谢对此的解释)
(如果需要,此处为架构)
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
【问题讨论】:
标签: ruby-on-rails ruby activerecord model