Chiara Ani
Chiara Ani

Reputation: 1083

"hasMany is not defined" error. Reflexive relationship in Emberjs

I get this error when I click a link to a route that retrieves the model with a reflexive relationship.

Uncaught ReferenceError: hasMany is not defined

This is my model in 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;
}

This is my route

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

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

This is my rails model in the backend

# 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

This is my serializer

# 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

Upvotes: 0

Views: 276

Answers (2)

Chiara Ani
Chiara Ani

Reputation: 1083

The problem mainly was my configuration:

# backend/config/initializers/active_model_serializers.rb
- ActiveModelSerializers.config.adapter = :json
+ ActiveModelSerializers.config.adapter = :json_api
// frontend/app/adapters/application.js
- import ActiveModelAdapter from 'active-model-adapter';
+ import JSONAPIAdapter from '@ember-data/adapter/json-api';
 
- export default ActiveModelAdapter.extend();
+ export default class ApplicationAdapter extends JSONAPIAdapter {
+ }
// app/models/section.js
- import Model, { attr } from '@ember-data/model';
+ import Model, { attr, belongsTo, hasMany } from '@ember-data/model';

Upvotes: 0

Lux
Lux

Reputation: 18240

you're missing the import here:

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

just add the import like this:

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

Upvotes: 2

Related Questions