Search code examples
javascriptruby-on-railsmodelember.jsdirectory-structure

How to set model's load order to avoid relation errors?


I have a folder models for model files. Each file contain one model. There are a lot of relations between models (hasMany, belongsTo). If I want to set hasMany relation then I need to have child model already defined otherwise I get an error:

Error: assertion failed: The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)

Because the model (App.Person in case of upper example) has not defined yet.

Here is one of the relation definition:

App.Seat = DS.Model.extend(
  number: DS.attr('number')
  tour: DS.belongsTo(App.Tour)
)

The models folder included like this:

//= require_tree ./models

I know the solution to define all the models (or at least which have relationships with each other) in one file.

Question: is there any other solution that allow to keep all the models in separate files?


Solution

  • I found a pretty simple solution: define all relation not as an object (ex. App.Tour):

    App.Seat = DS.Model.extend(
      number: DS.attr('number')
      tour: DS.belongsTo(App.Tour) # <<<<<<<<<<<============ ***here***
    )
    

    but as a string (ex. "App.Tour") so just put it in quotes:

    App.Seat = DS.Model.extend(
          number: DS.attr('number')
          tour: DS.belongsTo("App.Tour") # <<<<<<<<<<<============ ***here***
        )
    

    I think that this "workaround" is because of javascript limitation.

    UPDATED: Using strings is preferred by ember.js