Roy
Roy

Reputation: 1518

Why is this through association in Sails causing an error

I have two models: Species and Lands with a third model serving as the join table SpeciesLands allowing me to add additional attributes t.

Multiple species can occur on the same land. A single species can occur on multiple lands (M:M relationship). The following setup worked in SailsJS v0.12.13, but not when I upgraded to v1.x.

Error message

A through property was set on the attribute species on the lands model but no reference in the through model was found.

Models

My models are as follows (with unrelated attributes removed for brevity):

Species.js

  attributes: {

    ...

    lands: {
      collection: "lands",
      via: "land",
      through: "specieslands",
      description: "A species can be associated with one or more public lands"
    }

  },

Lands.js

  attributes {

    ...

    species: {
      collection: 'species',
      via: 'species',
      through: 'specieslands',
      description: 'A public land can be associated with one or more species'
    }
  }

SpeciesLands.js

  attributes: {

    population: {
      type: 'string',
      required: true,
      isIn: ['O+', 'O', 'P', 'U']
    },

    species: {
      model: 'species'
    },

    land: {
      model: 'lands'
    }
  }

Upvotes: 1

Views: 193

Answers (1)

NeoNexus DeMortis
NeoNexus DeMortis

Reputation: 1326

It is because your via attributes pointing to the wrong thing. They are the "pivot" point, if you will, to which the through association hinges. Also, you have land pluralization inconsistently in your collections.

Try something more like this:

Species.js

  attributes: {

    ...

    lands: {
      collection: 'land',
      via: 'species',
      through: 'specieslands',
      description: 'A species can be associated with one or more public lands'
    }

  },

Lands.js

  attributes {

    ...

    species: {
      collection: 'species',
      via: 'land',
      through: 'specieslands',
      description: 'A public land can be associated with one or more species'
    }
  }

SpeciesLands.js

  attributes: {

    population: {
      type: 'string',
      required: true,
      isIn: ['O+', 'O', 'P', 'U']
    },

    species: {
      model: 'species'
    },

    land: {
      model: 'lands'
    }
  }

Upvotes: 1

Related Questions