Use Model->create()

From now on, I’ll always use Model->create() before saving new data.

I’ve been using Model->create() for a series Model->save() calls (like in a loop) to initialize the model class for saving new information. But when I only need to do a single call to save(), I no longer call create() assuming that I’m starting with a new set of information. I was always able to get away with it until I had this bug that annoyed me for a few hours.

Long story short, I learned something: not only when doing multiple calls to Model->save(), you should also call Model->create() before saving if a previous call to Model->read() was made. Or better yet, always call Model->create() whenever you are about to save new data. There are cases the previous calls to save and read made are not that obvious, like in the beforeFilter() callbacks of the controller (or the parent::beforeFilter(), like in my case).

2 Responses to “Use Model->create()”

  1. Frank Says:

    Why is this sorry?

    Is this because you are creating a model object with read which is filled with data, then when you call say model->save($this->data) in your controller, the data in the model is saved rather than $this->data?

  2. rolan Says:

    No. It does save $this->data. The problem is, it updates/overwrites the previously read record with $this->data. The id of the record is kept at $this->Model->id after doing a read. When you do a save, the id is checked and if there is a value set, it uses that id for saving the record. To reset the value of the id (and any data “residue” in the model), a call to $this->Model->create() is needed.

Add Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>