【问题标题】:Adding search to an existing Rails index method向现有 Rails 索引方法添加搜索
【发布时间】:2013-12-08 10:32:45
【问题描述】:

我的 Rails 应用中有这个索引方法

  def index
    @articles = if params[:user_id]
      user = User.find(params[:user_id])
      user.articles.page(params[:page]).per_page(5)
    else
      @articles = current_user.articles.page(params[:page]).per_page(5)
    end
  end

这让我可以通过“/users/1/articles”之类的路线限制用户发布的帖子......一切都很好......

但我还想在文章内容上添加简单的单一过滤器,这样我就可以限制具有如下路径的文章:

/users/1/articles/foo 和 /articles/foo

其中 foo 是在文章内容字段上的搜索。有大量关于添加搜索的教程,但我不知道如何使它们与现有方法一起使用。另外,我不需要搜索表单或单独的搜索路径。

【问题讨论】:

  • 您的else 不应包含@articles =。放置@articles = if... 的全部意义在于,无论哪个分支执行,结果都将分配给@articles。你基本上已经写了你的 else 来做@articles = @articles = current_user....

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您的代码包含对“current_user”方法的引用。您是否使用设计或其他东西进行身份验证?如果是这种情况,您应该有一个 before_filter 用于 :authenticate!在控制器的顶部。获得代码后,您可以在操作中使用“current_user”(即索引方法)。

class YourController < ActionController::Base
  before_filter :authenticate!

  def index
    if params[:search_term]
      @articles = current_user.articles.where('content like ?', "%#{params[:search_term]}%").page(params[:page]).per_page(5)
    else
      @articles = current_user.articles.page(params[:page]).per_page(5)
    end
  end

另外,如果你想将搜索词作为 URI 的一部分传递,你需要在你的 routes.rb 中添加一个路由

get "users/contents/:search_term" => "users#index", as: :users_contents

【讨论】:

  • 我要补充一点,这只会做一个简单的搜索,看看文章内容中是否包含完整的搜索词参数。 “foo”将匹配“傻瓜”,“up down”将不匹配“up and down”等。这几乎是最低限度的搜索功能,并且有更好、更健壮和更高性能的方法。这可能不够好,也可能不够好,具体取决于具体情况。
  • 你是对的,@np。您可以使用诸如 Lucene/Solr 之类的东西。有一个名为“sunspot”的 gem,可以让您轻松使用 Solr 实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多