【问题标题】:Post.count not working properly on search results page (Rails)Post.count 在搜索结果页面(Rails)上无法正常工作
【发布时间】:2015-10-09 10:48:42
【问题描述】:

我有一个简单的 Rails 应用程序,它有一个显示 59 个帖子的索引页面。

问题是,如果我搜索某些内容,Post.count 会继续向我显示索引页面上的原始帖子数 - 例如,如果我搜索名为“Quilon”的帖子,我得到的搜索结果仅显示1 个帖子,但 Post.count 仍然显示原始帖子编号为 59。

我该如何解决这个问题?

INDEX.HTML.ERB 代码

<%= Post.count %> 

帖子控制器中的搜索功能

def index
    @posts = Post.all
    if params[:search]
      @posts = @posts.search(params[:search]).order("created_at DESC")
    end
    if params[:zagat_status].present?
      @posts = @posts.zagat_status(params[:zagat_status]).order("created_at DESC")
    end
  end

【问题讨论】:

  • 试试&lt;%= @posts.count %&gt;
  • 我认为你需要替换@posts.count
  • @posts.count 有效。谢谢!

标签: ruby-on-rails ruby


【解决方案1】:

在您的索引操作中,您使用某些条件缩小帖子的范围,因此您应该对 @posts 变量进行操作,而不是对模型 Post 本身进行操作。

这意味着你想使用@posts.count

【讨论】:

    【解决方案2】:

    你应该给&lt;%= @posts.count %&gt;而不是&lt;%= Post.count %&gt;&lt;%= Post.count %&gt; 返回所有记录中的count。和

    一样
    select count(*) from "posts"
    

    所以条件被忽略了。

    【讨论】:

      【解决方案3】:

      使用@posts.count 代替 Post.count

      【讨论】:

        猜你喜欢
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 2016-07-20
        • 1970-01-01
        • 2015-09-23
        • 2014-06-08
        • 1970-01-01
        相关资源
        最近更新 更多