Rails 5 的倒数无效

Rails 5 inverse of not working

我正在尝试 return JSON API show 操作

render json: user, include [:books, :friends, :comments]

问题是,如果我尝试在 UserBook 模型 类 中使用 inverse_of,如下所示:

用户序列化程序

class UserSerializer < ActiveModel::Serializer
  ...
  has_many :friends
  has_many :books, inverse_of: :author
  ...
end

图书序列化程序

class BookSerializer < ActiveModel::Serializer
  ...
  belongs_to :author, class_name: "User", inverse_of: :books
  ...
end

我得到一个错误:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: books.user_id: SELECT "books".* FROM "books" WHERE "books"."user_id" = ?):

如果我从我的用户序列化程序中删除 inverse_ofhas_many,那么我不会收到任何错误,但是 JSON 会被 returned不包含包含的关联。

同样,评论和用户模型之间也会发生同样的情况。

我是不是做错了什么?

我的两个模型的数据库模式是:

用户架构

create_table "users", force: :cascade do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.string   "username"
  t.string   "email"
  t.string   "password_digest"
  t.boolean  "banned"
  t.integer  "role_id"
  t.datetime "created_at",                           null: false
  t.datetime "updated_at",                           null: false
  t.string   "photo"
  t.boolean  "email_confirmed",      default: false
  t.string   "confirm_token"
  t.string   "password_reset_token"
  t.boolean  "show_private_info",    default: false
  t.boolean  "show_contact_info",    default: false
  t.index ["role_id"], name: "index_users_on_role_id"
end

书籍架构

create_table "books", force: :cascade do |t|
  t.string   "title"
  t.boolean  "adult_content"
  t.integer  "author_id"
  t.datetime "created_at",    null: false
  t.datetime "updated_at",    null: false
  t.boolean  "published"
  t.string   "cover"
  t.text     "blurb"
  t.index ["author_id"], name: "index_books_on_author_id"
end

当我使用以下命令生成我的 Book 模型时:

rails generate model books ... author:references

它创建了这个迁移文件:

class CreateBooks < ActiveRecord::Migration[5.0]
  def change
    create_table :books do |t|
      t.string :title
      t.boolean :adult_content
      t.references :author, foreign_key: true

      t.timestamps
    end
  end
end

我假设包括必要的外键设置...

尝试更改用户模型中的这一行(user.rb):

has_many :books, inverse_of: :author

has_many :books, inverse_of: :author, foreign_key: :author_id

你需要告诉 rails 你使用了什么 foreign_key 如果它不是默认的 one.And 关联应该在你的模型中声明,而不是序列化程序。在序列化程序中,您通过 "has_many" 添加键,inverse_of 在这里不起作用。