[Dbix-class] Dynamic defaults

Benjamin Martin benmartin at venda.com
Tue Nov 29 14:31:00 GMT 2011


hello,

I am not sure if I am doing the right thing so I ask here for advice 
please :)

I have 2 tables, chart and sections. A chart is made of multiple 
sections (chart has_many sections)
When I add a new section to a chart I want to give it a default name of 
'Section 1' or 'Section 2' and so on.

The DBIx::Class docs says that to provide defaults one should have a 
'new' method.
The Moose docs state to "never override new"

The above makes me think I am doing the wrong thing. In my Section class 
I have this:


around new => sub {
     my ($orig, $self) = (shift, shift);
     my ( $attrs ) = @_;

     if ( $attrs->{chart_id} ) {
         my $schema = $attrs->{-result_source}->schema;
         my $chart = $schema->resultset('Chart')->find( 
$attrs->{chart_id} );
         unless( defined $attrs->{name} ) {
             my $number_of_sections = $chart->sections->count;
             $attrs->{name} = 'Section ' . ($number_of_sections + 1);
         }
     }

     my $new = $self->$orig($attrs);
     return $new;
};


Is there a better way to achieve this?
It seems some what hacky to use '-result_source' ... is there a better way?

Thanks for any advice you can give.

tar,
-b






More information about the DBIx-Class mailing list