Rails 5反向不工作

时间:2016-12-29 09:02:06

标签: ruby-on-rails ruby-on-rails-5 active-model-serializers

我尝试返回show操作

的JSON API
render json: user, include [:books, :friends, :comments]

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

用户序列化程序

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

Book Serializer

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不包含所包含的关联。

同样,评论和用户模型之间也是如此。

我做错了吗?

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

用户架构

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

我认为这包括必要的外键设置......

1 个答案:

答案 0 :(得分:2)

尝试在用户模型(user.rb)中更改此行:

has_many :books, inverse_of: :author

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

你需要告诉rails你使用的foreign_key,如果它不是默认的那个。并且应该在模型中声明关联,而不是序列化器。在序列化程序中,您通过“has_many”添加键,inverse_of在这里不起作用。