【问题标题】:Rails - Associate three ModelsRails - 关联三个模型
【发布时间】: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


    【解决方案1】:

    这应该用'through'来完成吗?

    是的,Datum has_many books 通过authors 协会:

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

    books 可以通过以下方式选择:

    Datum.last.books
    

    它实际上是使用以下查询选择books

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

    【讨论】:

      【解决方案2】:

      如果要通过作者添加新书,则必须指定作者。所以你可以试试: nameofdatum.author.books.build ....

      您的代码nameofdatum.authors.books,您不能使用复数(作者)来添加新书。 希望能帮到你。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多