error-handling - 用cakephp保存数据不起作用

标签 error-handling save cakephp-2.0

我正在尝试使用load记录editsaveCakePHP 2.0,但是在generic error方法期间我收到了save,但没有帮助我了解问题出在哪里。

如果我尝试使用debug($this->User->invalidFields());,我会得到一个empty array,但是我会从false条件中得到$this->User->save()

这是我收到错误的 Controller 操作:

public function activate ($code = false) {
    if (!empty ($code)) {

        // if I printr $user I get the right user
        $user = $this->User->find('first', array('activation_key' => $code));

        if (!empty($user)) {
            $this->User->set(array (
                'activation_key' => null,
                'active' => 1
            ));

            if ($this->User->save()) {
                $this->render('activation_successful');
            } else {
                // I get this error
                $this->set('status', 'Save error message');
                $this->set('user_data', $user);
                $this->render('activation_fail');
            }
            debug($this->User->invalidFields());

        } else {
            $this->set('status', 'Account not found for this key');
            $this->render('activation_fail');
        }
    } else {
        $this->set('status', 'Empty key');
        $this->render('activation_fail');
    }
}

当我尝试操作test.com/users/activate/hashedkey时,我得到带有activation_fail消息的Save error message模板页面。

如果我对printr进行$user编码,则可以从cake的find方法中找到合适的用户。

我哪里错了?

最佳答案

我认为问题可能出在您查询用户记录的方式上。执行此操作时:

$user = $this->User->find('first', array('activation_key' => $code));

变量$user填充有用户记录作为数组。您检查以确保它不为空,然后继续;但是问题是没有填充$this->User。我认为如果您尝试debug($this->User->id),它将为空。 read() method按照您的思维方式工作。

您可以尝试使用$user数组中的ID来首先设置Model ID,如下所示:
if (!empty($user)) {
    $this->User->id = $user['User']['id']; // ensure the Model has the ID to use
    $this->User->set(array (
        'activation_key' => null,
        'active' => 1
    ));
    if ($this->User->save()) {
    ...

编辑:另外一种可能的方法是使用$user数组而不是修改当前模型。您说如果您使用debug($user)可以找回一个有效的用户,所以如果是这样,您可以执行以下操作:
if (!empty($user)) {
    $user['User']['activation_key'] = null;
    $user['User']['active'] = 1;
    if ($this->User->save($user)) {
    ...

此方法的工作方式与从$this->request->data接收表单数据的方式相同,并在本书的Saving Your Data部分中进行了介绍。

我很好奇,但是是否还有其他设置妨碍了您的设置。应用程序的其他部分能否正确写入数据库?您还应该检查以确保没有验证错误,例如其示例:
<?php
if ($this->Recipe->save($this->request->data)) {
    // handle the success.
}
debug($this->Recipe->validationErrors);

关于error-handling - 用cakephp保存数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100803/

相关文章:

cakephp - CakeEmail调试

c# - 给自己发500错误信息

c# - MVC中Http错误405的自定义错误处理程序

python - 如何克服python中的缩进错误?

c - 为什么这段代码不能继续?

php - cakephp 2.0 中的忘记密码功能

php - 如何在 cakePHP 2.x 中生成 CSV 文件?

python - 在 python 装饰器中引发异常是一个好的模式吗?

ios - 保存时向上计数

android - 试图将图片保存到尚未创建的特定图片文件夹