2011-04-15 21 views
0

我想改变我的编辑动作,以便用户只能编辑帖子,如果它是他们自己的。动作权限

下面是编辑动作之前,我改变了它:

function edit($id = null) { 
    $this->Post->id = $id; 
    if (empty($this->data)) { 
     $this->data = $this->Post->read(); 
    } else { 
     if ($this->Post->save($this->data)) { 
      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
     } 
    } 
} 

然后在这里就是我试图这样做,但没有成功:

function edit($id = null) { 
    if ($this->Auth->user('id') == $this->Post->user_id) { 
     $this->Post->id = $id; 
     if (empty($this->data)) { 
      $this->data = $this->Post->read(); 
     } else { 
      if ($this->Post->save($this->data)) { 
       $this->Session->setFlash('Your post has been updated.'); 
       $this->redirect(array('action' => 'index')); 
      } 
     } 
    } else { 
     $this->Session->setFlash('You are not authorized to edit that post.'); 
     $this->redirect(array('action' => 'index')); 
    } 
} 

任何人都知道我可以实现我的所需的功能?使用CakePHP的automagic有没有更简单的方法?

回答

0
public function edit($id) { 
    $post = $this->Post->find('first', array(
     'conditions' => array('Post.id' => $id, 'Post.user_id' => $this->Auth->user('id')), 
     'recursive' => -1 
    )); 
    if (!$post) { 
     $this->cakeError('error404'); 
    } 

    if ($this->data) { 
     $this->data['Post']['id'] = $id; 
     if ($this->Post->save($this->data)) { 
      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
     } 
    } else { 
     $this->data = $post; 
    } 
}