ruby – 如何结合两种不同的Mongoid标准
发布时间:2020-12-17 01:20:05 所属栏目:百科 来源:网络整理
导读:我的模型中定义了以下范围: scope :upcoming,- { where(:start_time.gt = Time.now).asc(:start_time) }scope :in_progress,- { now = Time.now where(:start_time.lte = now).where(:end_time.gte = now).asc(:start_time)} 我想创建另一个范围,它结合了两
我的模型中定义了以下范围:
scope :upcoming,-> { where(:start_time.gt => Time.now).asc(:start_time) } scope :in_progress,-> { now = Time.now where(:start_time.lte => now).where(:end_time.gte => now).asc(:start_time) } 我想创建另一个范围,它结合了两个名为current的范围的结果.我试过这样的事情: scope :current,-> { self.in_progress | self.upcoming } 但这最终只会将它们视为数组并将它们连接起来.这个问题是,当我尝试使用Model.current调用我的作用域时,我收到以下错误消息: NoMethodError: undefined method `as_conditions' for #<Array:0xaceb008> 这是因为它将Mongoid Criteria对象转换为数组,但我不希望这样.我希望该对象保留为Mongoid Criteria对象. 我真正想要的是in_progress集和即将到来的集合的结合. 有任何想法吗?谢谢. 解决方法
您可以尝试使用Mongoid的查询方法和取消引用标准的选择器来组成您的标准,但我不一定会建议这样做 – 请参阅下面的示例.我建议你制作第三个范围.请记住,这些范围对应于您希望高效的数据库查询,因此可能值得花时间检查和理解生成的结果和基础MongoDB查询.
模型 class Episode include Mongoid::Document field :name,type: String field :start_time,type: Time field :end_time,type: Time scope :upcoming,-> { where(:start_time.gt => Time.now).asc(:start_time) } scope :in_progress,-> { now = Time.now where(:start_time.lte => now).where(:end_time.gte => now).asc(:start_time) } scope :current,-> { any_of([upcoming.selector,in_progress.selector]) } scope :current_simpler,-> { where(:end_time.gte => Time.now) } end 测试 require 'test_helper' class EpisodeTest < ActiveSupport::TestCase def setup Episode.delete_all end test "scope composition" do #p Episode.in_progress #p Episode.upcoming #p Episode.current #p Episode.current_simpler in_progress_name = 'In Progress' upcoming_name = 'Upcoming' Episode.create(:name => in_progress_name,:start_time => Time.now,:end_time => 1.hour.from_now) Episode.create(:name => upcoming_name,:start_time => 1.hour.from_now,:end_time => 2.hours.from_now) assert_equal([in_progress_name],Episode.in_progress.to_a.map(&:name)) assert_equal([upcoming_name],Episode.upcoming.to_a.map(&:name)) assert_equal([in_progress_name,upcoming_name],Episode.current.to_a.map(&:name)) assert_equal([in_progress_name,Episode.current_simpler.to_a.map(&:name)) end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- vb.net – Redim boolean Array vs enumerate and set
- 如何在初始化方法中干掉我的ruby异常?
- iphone – 搜索栏与搜索栏和搜索显示控制器有什么区别?
- 在sqlite数据库中安装android-db-shm和db-wal
- XML解析api的对比(JAXB vs SAX)
- objective-c – iphone隐藏UISearchDisplayController结果?
- iphone – 带UIPageControl的GMGridView
- 查看weblogic版本号
- Postgresql standby(备机只读)环境搭建
- 正则表达式学习笔记005--脱字符和美元符的认识与应用