[Dbix-class] mk_group_accessors and create

Martin Bendix martinbendix at yahoo.co.uk
Sat Nov 27 15:33:43 GMT 2010


Hi,

This is more a question out of curiosity than anything else, as I know that 
there are other fairly simple ways to achieve the desired end result.  I thought 
it worth asking though, just in case I am missing something fundamental.

I'd like be able to include non-column data in the 
'DBIx::Class::ResultSet->create' method, so that I can grab the data and do 
something with it, but I don't know if it possible to do this using 
'mk_group_accessors' (via Class::Accessor::Grouped).

As a somewhat simplified example, I have two tables with a one-to-many 
relationship: 'contact' and 'title'.

The 'contact' table has these columns:

    id
    title_id
    first_name
    last_name

The 'title' table has these columns:

    id
    title

The 'title' table is pre-populated with titles (Mr, Mrs, Miss, etc.), and these 
will be displayed in a drop-down list from which the user can choose.  I would 
also like to give the user the opportunity to add more titles via an 'other' 
field on a form.

Instead of checking for the existence of this extra field, and using 
'create_related' to insert this into the title table, I was thinking that it 
might be possible to create a non-column data accessor ('new_title', for 
example) in the 'contact' class, and pass a value to this as part the call to 
the 'create' method.  I could then use the accessor to grab the new value and 
insert it into the 'title' table.

Alas, I have not been able to get this to work, as the 'create' method doesn't 
appear to allow me to do this.  Is it simply the case that this is not possible, 
or am I doing something wrong?

Here's an example of what I have tried:

    ## All works as expected, until I try the 'create' method:

    __PACKAGE__->mk_group_accessors( simple => 'new_title' );

    # Override accessor get and set methods if required:

    sub get_simple {
        my ($self, $field) = @_;
    
        # Return value for $field.
    }

    sub set_simple {
        my ($self, $field, $value) = @_;

        # Do something with $field and $value here.
    }

    # Elsewhere...

    # Find a row:
    my $row = $rs->find({ id => $id });

    # Set the new title value:
    $row->new_title('Sir');

    # Get the new title value:
    my $new_title = $row->new_title;

    # Update the row:
    $row->update();

    ## But this fails with 'no such column new_title':

    # Create a new row, and include non-column data:
    $rs->create({
        first_name => 'Sherlock',
        last_name  => 'Holmes',
        new_title  => 'Dr',
    });




Many thanks,

Martin


      



More information about the DBIx-Class mailing list