【问题标题】:Rails 3 Active Record Initialize Search ChainingRails 3 Active Record 初始化搜索链
【发布时间】:2010-08-31 21:23:28
【问题描述】:

我有一个在 Rails 3 应用程序中执行基本过滤的搜索功能(使用新的方法链接)。过滤使用可选参数,看起来像这样:

class User < ActiveRecord::Base

  def self.search(params = {})
    users = User.?

    users = users.where(:sin => params[:sin]) if params[:sin]
    ...
    users = users.where("name LIKE :q", :q => "%params[:q]%") if params[:q]
  end

end

我不确定如何设置默认用户以包含所有用户。如果没有指定参数,我希望搜索功能返回所有记录,否则过滤。有任何想法吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:
    class User < ActiveRecord::Base
    
      def self.search(params = {})
        users = User.scoped
    
        users = users.where(:sin => params[:sin]) if params[:sin]
        ...
        users = users.where("name LIKE :q", :q => "%params[:q]%") if params[:q]
      end
    
    end
    

    【讨论】:

    • 谢谢西蒙妮!正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多