2009-11-04 58 views
2

我在我的控制器頁面有問題。順便說一句我想要執行本地主機:3000 /文章/ donat?author_id = 4,這意味着我只想看看文章與author_id = 4 我已經嘗試過這樣的類型代碼。如何過濾在ActionController中?

def donat 
    @title = "All blog entries" 
    if params[:author_id] == :author_id 
     @articles = Article.published.find_by_params(author_id) 
    else 
     @articles = Article.published 
    end 
    @articles = @articles.paginate :page => params[:page], :per_page => 20 
    render :template => 'home/index' 
    end 

它不工作。你對這個案子有什麼建議嗎?

回答

8

你想爲此嵌套資源,而getting started guide就是一個很好的例子。進一步

private 
    def find_author 
    @author = Author.find(params[:author_id]) if params[:author_id] 
    @articles = @author ? @author.articles : Article 
    end 

,然後向上控制器,我需要找到文章:

個人而言,我把這個在我的控制器的頂部:

before_filter :find_author 

這在底部:

@articles.find(params[:id]) 

這將適當的範圍。

+0

如何find_author習慣這裏打了個電話,@articles被置?你忘了提及它需要在before_filter中嗎? – rnicholson 2009-11-04 14:59:04

+0

事實上,Emfi確定了這一點,我認爲我仍然會將它們用於索引和新行爲。 – 2009-11-04 20:28:16

+0

我有同樣的問題。這是一個好習慣還是應該避免? – Federico 2014-06-04 20:37:57

1

你應該做的雷達顯示(使用嵌套資源),但是這應該立即解決的問題:

def donat 
    @title = "All blog entries" 
    if params[:author_id] # This is where the problem is. 
    published_articles = Article.published.find_by_params(author_id) 
    else 
    published_articles = Article.published 
    end 
    @articles = published_articles.paginate :page => params[:page], :per_page => 20 
    render :template => 'home/index' 
end