[Catalyst] Template creates objects via belongs_to autovivification

Jason Kohles email at jasonkohles.com
Wed Jun 13 15:56:34 GMT 2007


On Jun 13, 2007, at 8:17 AM, Matt Rosin wrote:

> The thing is, then I decided to let admins add new transactions  
> without an associated customer, to record in the database  
> transactions that were made offline. Instead of assigning  
> r.customer to the id of the company running the system I just say 0  
> (not using nulls). What happens is, somehow the template forces  
> Catalyst (DBIx::Class) to create a NEW CUSTOMER if there wasn't one  
> already. This is bad, bad, bad. Every time an admin views the list  
> of transactions, it seems I get 4 blank customer records silently  
> added simultaneously, or maybe even more, depending on what kind of  
> records are shown on the current page it seems. I discovered this  
> by matching the FastCGI error log (which is where the -Debug output  
> goes.. all 300MB of it...) against the modification date of the new  
> customer records.
>
The relationship docs imply that belongs_to will do the right thing  
if the relationship is optional, but also indicates that it  
determines if the relationship is optional by whether the foreign key  
can be NULL or not, if you have defined that column as NOT NULL, you  
may be running into problems....

        If the relationship is optional -- i.e. the column containing  
the
        foreign key can be NULL -- then the belongs_to relationship  
does the
        right thing. Thus, in the example above "$obj->author" would  
return
        "undef".  However in this case you would probably want to set  
the
        "join_type" attribute so that a "LEFT JOIN" is done, which makes
        complex resultsets involving "join" or "prefetch" operations  
work
        correctly.  The modified declaration is shown below:

          # in a Book class (where Author has_many Books)
          __PACKAGE__->belongs_to(author => 'My::DBIC::Schema::Author',
                                  'author', {join_type => 'left'});

-- 
Jason Kohles
email at jasonkohles.com
http://www.jasonkohles.com/
"A witty saying proves nothing."  -- Voltaire





More information about the Catalyst mailing list