5

I have a ember-data model which has a belongsTo relationship and I'd like test whether there is any value (aka, foreign key reference) in this relationship. I initially thought I could just state:

if(myModel.rel !== null) {
    // do something now that belongsTo relationship has a value
}

But of course this doesn't work because myModel.rel would never be null and instead is some sort of Ember Data object. Ok fine. I adjusted this to:

if(myModel.rel.content !== null) {
    // do something now that belongsTo relationship has a value
}

This does work but I feel like maybe this is a bit too "hacky" ... is there a cleaner, more API driven way of stating this conditional in Ember Data?

ken
  • 8,763
  • 11
  • 72
  • 133
  • There is no existing API yet, but it may be added: https://github.com/ebryn/ember-model/issues/163 – medokin Oct 14 '15 at 14:27

2 Answers2

1

I know this is an old question, but I have done it this way (I don't know of an official way).

if (model.get('relationshipName.id')) {
  // there's and ID present, so it means theres a value for the foreign key
}

model.relationshipName.id returns undefined when there's no value and the id when there's a value.

Pedro Rio
  • 1,444
  • 11
  • 16
  • 1
    Note that this is less useful if you want to check the existence of a relationship that isn't yet persisted, because it may not have an ID yet. – Justin Workman Jan 25 '22 at 00:58
1

In newer versions of Ember-Data there is an API to get the value of a relationship like so:

model.belongsTo('relationshipName').value()

And then you can use the isPresent helper to check against null or undefined in a more idiomatic way:

import { isPresent } from '@ember/utils';

const relatedRecord = model.belongsTo('relationshipName').value();
const relatedRecordExists = isPresent(relatedRecord);

Or simply use the return value in an if statement without coercing to boolean, e.g.:

if (relatedRecord) {
  ...
}

References

Justin Workman
  • 688
  • 6
  • 12