Rails中scopes的几种使用方法
来源:互联网 发布:淘宝运营主要做什么 编辑:程序博客网 时间:2024/06/06 06:49
不传参数使用scope方法
class User < ActiveRecord::Base
scope :finduser, {where(status: 'username')}
scope :has_content, {joins(:comment).where("comments.content is not null")}
end
传参数使用scope方法
class User < ActiveRecord::Base
scope :finduser, ->(username){ where(username: username) }
scope :has_content, ->(content){joins(:comment).where('comments.content = ?', content)}
end
class User < ActiveRecord::Base
scope :finduser, Proc.new { |username| where(username: username) }
scope :has_content, Proc.new{joins(:comment).where('comments.content = ?', content)}
end
class User < ActiveRecord::Base
scope :finduser, lambda { |username| where(username: username) }
scope :has_content, lambda{joins(:comment).where('comments.content = ?', content)}
end
class User < ActiveRecord::Base
def self.finduser username
where(username: username) unless username.empty?
end
def self.has_content content
lambda{joins(:comment).where('comments.content = ?', content)}
end
end
总结
当逻辑是简单的where/order这样的查询时使用scope;涉及到复杂查询时,使用类方法。
另外,当需要做一些扩展时,作为Active Record提供的一个特性,我还是推荐使用scope。
- Rails中scopes的几种使用方法
- Rails中session的使用方法
- Scopes in Rails 3
- Rails 中有关代理的使用方法
- Rails 中关于 try() 的使用方法
- rails 中 几种动态 查询 的实现方式
- android 中定时器的几种使用方法
- jQuery中setTimeout的几种使用方法
- jQuery中setTimeout的几种使用方法
- jQuery中setTimeout的几种使用方法
- jQuery中setTimeout的几种使用方法
- jQuery中setTimeout的几种使用方法
- Android中Intent的几种使用方法
- iOS中全局变量的几种使用方法
- Python中数组的几种使用方法
- ' * '的几种使用方法
- Spring中scopes属性。
- 在iPhone开发中,全局变量的几种使用方法
- Java面试宝典(三)
- Android开发中获取尺寸(View和屏幕分辨率)
- 第一次使用Android Studio时你应该知道的一切配置
- LLVM代码研读(1)---- 安装篇
- Unity中为UGUI精灵自定义事件响应区域
- Rails中scopes的几种使用方法
- 教你Windows平台安装配置Hadoop2.5.2(不借助cygwin)
- ContentProvider实现数据共享
- java学习(1)-jdk环境安装以及常用DOS命令
- ionic开发中,键盘弹出遮挡div内元素的解决方案
- 下拉菜单
- 子查询
- Android 5.x 权限问题解决方法
- C++实验4-百钱买百鸡问题