使用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`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值