首页 > 解决方案 > “hasMany 未定义”错误。Emberjs 中的反身关系

问题描述

当我单击指向检索具有自反关系的模型的路由的链接时,我收到此错误。

Uncaught ReferenceError: hasMany is not defined

这是我在 Ember 中的模型

// app/models/section.js
import Model, { attr } from '@ember-data/model';

export default class SectionModel extends Model {
  @attr('string') title;
  @attr('string') body;
  @attr('number') order;
  @attr('string') slug;
  @hasMany('section', { inverse: 'superior' }) subsections;
  @belongsTo('section', { inverse: 'subsections' }) superior;
}

这是我的路线

import Route from '@ember/routing/route';

export default class DocsRoute extends Route {
    model() {
        return this.store.findAll('section');
    }
}

这是我在后端的 Rails 模型

# app/models/section.rb
# frozen_string_literal: true

class Section < ApplicationRecord
  validates_presence_of :title
  extend FriendlyId
  friendly_id :title, use: :slugged

  validates :order, numericality: { only_integer: true }
  default_scope -> { order(:order) }

  has_many :subsections, class_name: "Section",
                          foreign_key: "superior_id"
  belongs_to :superior, class_name: "Section", optional: true

  scope :root, -> { where(superior: nil) }
end

这是我的序列化器

# app/serializers/section_serializer.rb
# frozen_string_literal: true

class SectionSerializer < ActiveModel::Serializer
  attributes :id, :title, :slug, :body, :order
  belongs_to :superior
  has_many :subsections
end

标签: javascriptruby-on-railsrubyember.js

解决方案


您在这里缺少导入:

import Model, { attr } from '@ember-data/model';

只需像这样添加导入:

import Model, { attr, hasMany } from '@ember-data/model';

推荐阅读