Ticket #17 (new defect)

Opened 6 years ago

Last modified 6 years ago

Auto-saving habtm records fails when done via save() instead of save($attributes)

Reported by: Alderete Owned by: somebody
Priority: high Milestone: 1.0
Component: Active Record Version: 0.11.0
Severity: major Keywords:
Cc:

Description

The ActiveRecord?->save() method delegates actual creation of a new record to the private add_record() method. add_record in turn calls $this->add_habtm_records($this->id) to create the appropriate HABTM records in the map/join/association table.

But, add_habtm_records() only does its work if the member variable $this->habtm_attributes is already set. And that array is only set in save() if the attributes are passed into save() itself:

    function save($attributes = null, $dont_validate = false) {
        if(!is_null($attributes)) {
            $this->update_attributes($attributes);
        }

So if the HABTM items are attached like so:

$story = new Story($form_data);
$story->categories = $cats_not_from_form;
$story->save();

Then the appropriate HABTM records will not be added, because they got added to the Story entity *after* the habtm_attributes member variable was updated.

I think the fix is to update the habtm_attributes variable in the save() method itself, instead of skipping over that if no attributes are passed to save() itself.

Or am I half-baked, and I should save with the attributes in method, ala:

$story->save(array('categories' => $cats_not_from_form));

Change History

Changed 6 years ago by john

# This line here will set your habtm and be auto saved if its in the form_data array
$story = new Story($form_data); 

# calling this line wipes out what the constructor just did since habtm expects in certain format
$story->categories = $cats_not_from_form;
$story->save();

Changed 6 years ago by john

  • summary changed from Jean to Auto-saving habtm records fails when done via save() instead of save($attributes)

Changed 6 years ago by john

  • severity changed from 1 to major
  • cc Jean removed
  • component changed from 1 to Active Record
  • priority changed from 1 to high
  • version changed from 1 to 0.11.0
  • milestone changed from 1 to 1.0
  • keywords Jean removed
Note: See TracTickets for help on using tickets.