Ruby on rails 向现有Rails索引方法添加搜索

Ruby on rails 向现有Rails索引方法添加搜索,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我在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

我在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”这样的路由限制用户的帖子。。。一切都好

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

/用户/1/articles/foo 和 /物品/食物


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

您的代码包含对“当前用户”方法的引用。您是否使用Desive或其他东西进行身份验证?如果是这种情况,您应该有一个before_过滤器:authenticate!在控制器的顶部。一旦有了代码,就可以在操作中使用“current_user”(即index方法)


您的
else
不应包含
@articles=
。放置
@articles=如果…
的全部要点是,无论哪个分支执行,结果都将分配给
@articles
。您基本上已经编写了else to do
@articles=@articles=current_user….
。我想补充一点,这将只执行一个简单的搜索,以查看完整的搜索条件参数是否包含在文章内容中。“foo”将匹配“傻瓜”,“up-down”将不匹配“up-and-down”,等等。这几乎是最简单的搜索功能,有更好、更健壮、性能更高的方法。这可能不够好,也可能不够好,这取决于具体情况。你是对的,@np。您可以使用Lucene/Solr之类的工具。有一个叫做“太阳黑子”的gem,它允许您轻松地使用Solr实现。
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
get "users/contents/:search_term" => "users#index", as: :users_contents