2014-12-03 55 views
0

我正在尝试实现用户查找其他用户的简单搜索表单。我一直在网上查找相当一段时间,但很多资源似乎是过时的,无论是3号轨道还是退役的宝石...rails 4简单的搜索表单,供用户查找对方

任何人都可以指向我最近的rails 4资源进行简单的搜索或显示我的骨架代码开始?先谢谢你!

回答

1

https://github.com/jhund/filterrific

scope :search_query, lambda { |query| 
    return nil if query.blank? 

    terms = query.to_s.downcase.split(/\s+/) 

    # replace "*" with "%" for wildcard searches, 
    # append '%', remove duplicate '%'s 
    terms = terms.map { |e| 
    (e.gsub('*', '%') + '%').gsub(/%+/, '%') 
    } 

    # configure number of OR conditions for provision 
    # of interpolation arguments. Adjust this if you 
    # change the number of OR conditions. 
    num_or_conds = 2 
    sql = "(LOWER(foo.first_name) LIKE ? OR LOWER(foo.last_name LIKE ?)" 

    where(
    terms.map { |term| sql }.join(' AND '), *terms.map { |e| [e] * num_or_conds }.flatten 
) 
} 

这将是由任一first_name的或姓氏搜索用户的一个简单的例子。 Filterrific是相当不错的,但如果您有多条记录,则可以在查询时执行查询。

+0

Vlad SQL中存在语法错误。在'foo.last_name' - 'sql =“(LOWER(foo.first_name)LIKE?或LOWER(foo.last_name)LIKE?)?之后缺少一个大括号?”“ - 我尝试添加它,但编辑时需要6个以上的字符。 ' – Brett 2016-08-18 18:30:12

0

对用户的一个非常简单的搜索用户名,你可以在你的观点做:

<%= form_tag users_path, :method => 'get', :id => 'users_search' do %> 
    <p> 
     <%= text_field_tag :search, params[:search] %> 
     <%= submit_tag "Search", :name => nil %> 
    </p> 
<% end %> 

在您的用户模型,你必须定义一个“搜索”的方法:

#users_controller.rb 
def self.search(user_name) 
    if user_name 
     user_name.downcase! 
     where('LOWER(name) LIKE ?', "%#{user_name}%") 
    else 
     all 
    end 
end 

最后是你的控制器,你可以调用这个方法:

def index 
    @users = User.search(params[:search]) 
end 

途径可以被定义为像您的默认RO一个GET ute为页面:

#routes.rb 
resources :users