2012-02-29 136 views
2

我有以下兩種途徑在我的應用程序:路由不工作

Router::connect('/posts/:id', 
        array('controller' => 'posts', 'action' => 'view'), 
        array('id' => '[A-Za-z0-9\._-]+', 'pass' => array('id'))); 

    Router::connect('/posts/:slug-:id', 
        array('controller' => 'posts', 'action' => 'view'), 
        array(
         'id' => '[A-Za-z0-9\._-]+', 
         'slug' => '[A-Za-z0-9\._-]+', 
         'pass' => array('id', 'slug') 
        )); 

和示例網址是:

/posts/This_is_the_first_post-1

但是它會顯示一個404,但如果我將id前的網址-更改爲/,它將起作用:/任何想法是什麼問題?是正則表達式造成的?

這裏是我的觀點方法:

function view ($id = null, $slug = null) 
    { 
     $post = $this->Post->find('first',array('contain'=>array('User'=>'Profile'),'conditions'=>array('Post.id'=>$id))); 

     if (!$post) 
     { 
      throw new NotFoundException('404'); 
     } 
     else if($post['Post']['status'] == '0') // 0=draft 1=closed 2=open 
     { 
      if($post['Post']['user_id'] == $this->Auth->user('id')) 
      { 
       $this->Session->setFlash('Your post has NOT been published yet'); 
      } 
      else 
      { 
       throw new NotFoundException('404'); 
      } 
     } 

     if (Inflector::slug($post['Post']['title']) != $slug || $slug = null) 
     { 
      $this->redirect(array('id'=>$post['Post']['id'],'slug'=>Inflector::slug($post['Post']['title']))); 
     } 

     $this->set(compact('post')); 
    } 

回答

2

它看起來由正則表達式引起的。在第一條路線中,您允許-,因此它可能無法區分第二條路線,其中:id應該遵循-

Router::connect('/posts/:id', 
       array('controller' => 'posts', 'action' => 'view'), 
       array('id' => '[A-Za-z0-9\._]+', 'pass' => array('id'))); 
       //---Removed hyphen-----^^^^^^ 

Router::connect('/posts/:slug-:id', 
       array('controller' => 'posts', 'action' => 'view'), 
       array(
        'id' => '[A-Za-z0-9\._]+', 
       //---Removed hyphen-----^^^^^^ 
        'slug' => '[A-Za-z0-9\._]+', 
       //---Removed hyphen-----^^^^^^ 
        'pass' => array('id', 'slug') 
       )); 
+0

乾杯爲:) – Cameron 2012-02-29 21:38:18

+0

我實際上試着問這個問題之前刪除連字符自己,但它仍然打破了:/絕拆錯了人或事物。再次歡呼。 – Cameron 2012-02-29 21:42:59