将搜索添加到现有Rails索引方法

时间:2013-12-08 01:49:58

标签: 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
  end

允许我限制用户使用“/ users / 1 / articles”等路线限制帖子......一切都很好......

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

/用户/ 1 /物品/富 和 /物品/富

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

1 个答案:

答案 0 :(得分:1)

您的代码包含对“current_user”方法的引用。您使用Devise或其他东西进行身份验证吗?如果是这种情况,你应该有一个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的一部分传递,则需要为路由添加路由.rb

get "users/contents/:search_term" => "users#index", as: :users_contents
相关问题