我的控制器页面有问题。顺便说一下,我想执行localhost:3000 / article / donat?author_id = 4,这意味着我只想查看author_id = 4的文章 我尝试过这样的类型代码。
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
它不起作用。你对这个案子有什么建议吗?
答案 0 :(得分:8)
您需要嵌套资源,而getting started guide就是一个很好的例子。
就个人而言,我会把它放在我的控制器顶部:
before_filter :find_author
这就在底部:
private
def find_author
@author = Author.find(params[:author_id]) if params[:author_id]
@articles = @author ? @author.articles : Article
end
然后在我需要找到文章的控制器中进一步向上:
@articles.find(params[:id])
适当的范围。
答案 1 :(得分:1)
你应该像Radar建议的那样(使用嵌套资源),但是这应该可以解决你当前的问题:
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