Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation with inherit #36

Closed
AntonyDeveau opened this issue May 20, 2016 · 4 comments
Closed

Validation with inherit #36

AntonyDeveau opened this issue May 20, 2016 · 4 comments

Comments

@AntonyDeveau
Copy link

Hi,

I have a model 'property' and 'flat'.
Flat inherits from property, but when i declare validations in both, only 'Flat' validators show, because they are rewritten.
How can I use validations from the parent in the child class?

@esbanarango
Copy link
Owner

#33

@GabrielCW
Copy link

GabrielCW commented Sep 19, 2016

@AntonyDeveau and I came across a solution for simple cases of inheritance. It goes no further than exporting and merging validation properties, but it's a start.

Here's an example:

parent.js

export let validations = {
  aFieldInTheParent: {
    presence: {message: 'This field must be there'}
};

export default Resource.extend({
  aFieldInTheParent: DS.attr('string'),
  validations: validations
});

child.js

import Parent from './parent';
import { parentValidations } from './parent';

export default Parent.extend({
  aFieldInTheChild: DS.attr('number'),
  validations: Ember.merge(parentValidations, {
    aFieldInTheChild: {
      numericality: {
        greaterThan: 0,
        message: 'This must be greater than 0.'
      }
    }
  })
});

Note that we haven't tested whether added validations on then parent's fields in the child work. This depends on how Ember.merge works, although this can be overriden by your own merging logic.

Hope that may help someone (@NullVoxPopuli)

@NullVoxPopuli
Copy link

thanks for the merging idea!

@GabrielCW
Copy link

GabrielCW commented Sep 21, 2016

Turns out merging as I wrote it actually changed the parent's validations and put the child's instead.
Validations should actually be copied first, like so:

child.js

import Parent from './parent';
import { parentValidations } from './parent';

export default Parent.extend({
  aFieldInTheChild: DS.attr('number'),
  validations: Ember.merge(Ember.copy(parentValidations, true), {
    aFieldInTheChild: {
      numericality: {
        greaterThan: 0,
        message: 'This must be greater than 0.'
      }
    }
  })
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants