使用scope 链接多个where条件_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > 使用scope 链接多个where条件

使用scope 链接多个where条件

 2013/5/19 14:49:28  夜鸣猪  程序员俱乐部  我要评论(0)
  • 摘要:scope:by_category,(lambdado|category_id|where(category_id:category_id)unlesscategory_id.nil?end)scope:by_district,(lambdado|district_id|where(district_id:district_id)unlessdistrict_id.nil?end)#ifdistrict是nil就会返回全部Client.by_category(category)
  • 标签:使用
class="ruby" name="code">

  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`

发表评论
用户名: 匿名