2014-09-21 56 views
0

我的目標是在我的帖子頁面中有一個標籤雲,這將允許用戶通過單擊標籤來過濾帖子。但是,我遇到了一個未定義的方法「做了如下修改我的Post_Controller方法之後TOTAL_PAGES」錯誤:用will_paginate運行未定義的方法`total_pages'

class PostsController < ApplicationController 

    def index 
    if params[:tag] 
     @posts = Post.tagged_with(params[:tag]) 
    else 
     @posts = Post.visible_to(current_user).where("posts.created_at > ?", 7.days.ago).paginate(page: params[:page], per_page: 10) 
    end 
    end 
end 

我試圖使用行爲-AS-加標籤上的寶石,而這種邏輯將展示我用適當的標籤帖子

問題發生在帖子/ index.html.erb景觀:

<div class="row"> 
    <div class="col-md-8"> 
    <h1> Trending </h1> 
    <p class="lead"> Active posts this week </p> 
    <div id="tag_cloud"> 
    Tag Cloud: 
    <% tag_cloud Post.tag_counts, %w[s m l] do |tag, css_class| %> 
    <%= link_to tag.name, tag_path(tag.name), class: css_class %> 
    <% end %> 
    </div> 
    <%= render partial: 'posts/post', collection: @posts %> 
     <%= will_paginate @posts %> 
    </div> 
    <div class="col-md-4"> 
    </div> 
</div> 

的will_paginate線將不會呈現該網頁上的所有崗位的解決辦法是擺脫<%= will_paginate @posts %>並替換

@posts = Post.visible_to(current_user).where("posts.created_at > ?", 7.days.ago).paginate(page: params[:page], per_page: 10) 

@posts = Post.all。但是,這給了我一整頁的帖子,這很醜陋。有誰知道我爲什麼遇到未定義的方法'total_pages'錯誤?

enter image description here

+0

有幾個相同的SO這個問題,花一點時間來通過他們去 - 相信你會找到答案 – 2014-09-21 20:50:04

+0

是當params [:tag]被設置或沒有發生錯誤? – 2014-09-21 20:55:43

+0

@FrederickCheung該頁面可以正常加載帖子和雲標籤。然而,只有當我點擊一個標籤來過濾帖子時,錯誤纔會發生。 params [:tag]爲false時發生錯誤。 – ShaunK 2014-09-21 20:58:16

回答

2

看來,當你發送一個標籤(PARAMS [:標籤])就像是獲取職位與

@posts = Post.tagged_with(params[:tag]) 

這是缺乏將分頁電話。我相信你能得到它通過增加將分頁範圍,像這樣的工作:

@posts = Post.tagged_with(params[:tag]).paginate(...) 
+0

哦,天啊..這是問題..我認爲這是第二行我的if else子句導致錯誤... – ShaunK 2014-09-21 21:06:03