【问题标题】:rails 4 simple search form for users to find each otherrails 4 简单的搜索表单,供用户相互查找
【发布时间】:2014-12-03 22:00:29
【问题描述】:

我正在尝试为用户实现简单的搜索表单以查找其他用户。我已经在网上浏览了很长时间,但是很多资源似乎已经过时,无论是对于 rails 3 还是退休的 gems。 ..

谁能指出我最近的 rails 4 资源以进行简单搜索或向我展示开始的框架代码?提前谢谢你!

【问题讨论】:

    标签: search ruby-on-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 或 last_name 搜索用户的简单示例。 Filterrific 非常好,但如果您有很多记录,它在查询时可能会很重。

    【讨论】:

    • 弗拉德 SQL 中存在语法错误。 foo.last_name - sql = "(LOWER(foo.first_name) LIKE ? OR LOWER(foo.last_name) LIKE ?)" - i tried adding it but requires more than 6 characters on the edit. 之后缺少右括号
    【解决方案2】:

    对于用户用户名的非常简单的搜索,您可以在您的视图中进行:

    <%= 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
    

    路由可以定义为 GET,就像页面的默认路由一样:

    #routes.rb
    resources :users
    

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 2015-06-15
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多