Help language development. Donate to The Perl Foundation

ORM::ActiveRecord cpan:GDONALD last updated on 2019-10-24

t/002-validate-unique-scope.t6
use v6.d;
use lib 'lib';
use ORM::ActiveRecord::Model;
use Test;

class Subscription {...}

class User is Model {
  submethod BUILD {
    self.has-many: subscriptions => class => Subscription;

    self.validate: 'fname', { :presence }
  }
}

class Magazine is Model {
  submethod BUILD {
    self.has-many: subscriptions => class => Subscription;

    self.validate: 'title', { :presence }
  }
}

class Subscription is Model {
  submethod BUILD {
    self.belongs-to: user => class => User;
    self.belongs-to: magazine => class => Magazine;

    self.validate: 'user_id', { uniqueness => scope => :magazine_id }
  }
}

plan 3;

%*ENV<DISABLE-SQL-LOG> = True;

my $subscription;

my $user = User.create({fname => 'Greg'});
my $magazine = Magazine.create({title => 'Mad'});
$subscription = Subscription.create({:$user, :$magazine});
ok $subscription.is-valid;

$subscription = Subscription.build({:$user, :$magazine});
nok $subscription.is-valid;
ok $subscription.errors.user_id[0] eq 'must be unique';

Subscription.destroy-all;
Magazine.destroy-all;
User.destroy-all;