代码之家  ›  专栏  ›  技术社区  ›  Ahmad Ramdani

如何过滤ActionController?

  •  2
  • Ahmad Ramdani  · 技术社区  · 15 年前

    我的控制器页面有问题。顺便问一下,我想执行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
    

    它不工作。你对这个案子有什么建议吗?

    2 回复  |  直到 15 年前
        1
  •  8
  •   Ryan Bigg Andrés Bonilla    15 年前

    您需要此的嵌套资源,以及 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])
    

    这将适当地确定范围。

        2
  •  1
  •   jonnii    15 年前

    你应该按照雷达的建议去做(使用嵌套的资源),但是这可以解决你当前的问题:

    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