使用scope 链接多个where条件


  scope :by_category, (lambda do |category_id|
    where(category_id: category_id) unless category_id.nil?
  end)
  scope :by_district, (lambda do |district_id|
    where(district_id: district_id) unless district_id.nil?
  end)
#if district 是nil就会返回全部
Client.by_category(category).by_district(district)




class User
  scope :by_age, lambda do |age|
    joins(:profile).where('profile.age = ?', age) unless age.nil?
  end
  scope :by_name, lambda{ |name| where(name: name) unless name.nil? }
  scope :by_email, lambda do |email|
    joins(:profile).where('profile.email = ?', email) unless email.nil?
  end
end




wheres = [:id, :email].map{|key| params.has_key?(key) ? {key => params[key]} : {} }\
                      .inject({}){|hash, injected| hash.merge!(injected)}
@users = User.where(wheres).limit(10)





#user.rb
scope :by_status, lambda { |status| where(:status => status) unless status.blank? }

# If you need to execute a block of code you can use the following syntax
scope :by_status, (lambda do |status|
where(:active => status) unless status.blank?
end)


#Active users
pry(main)> User.by_status(1)
SELECT `users`.* FROM `users` WHERE `users`.`active` = 1

#Inactive users
pry(main)> User.by_status(0)
SELECT `users`.* FROM `users` WHERE `users`.`active` = 0

#All users
pry(main)> User.by_status(nil)
SELECT `users`.* FROM `users`

你可能感兴趣的:(Ruby,Rails)