ruby-on-rails – Rails MongoID – 按属性查询

我有这样的模型:
class Lesson
  include Mongoid::Document

  field :title,:type => String
  field :category,:type => String
  field :price,:type => Float
  field :description,:type => String
  field :user_id,:type => String


  validates_presence_of :title
  validates_presence_of :category
  validates_presence_of :price
  validates_presence_of :user_id

  attr_accessible :title,:category,:description,:price

end

我试图像这样查询

@lessons_by_user = Lesson.find_by_user_id current_user.id

我得到了:

undefined method `find_by_user_id’ for Lesson:Class

如何通过MongoID中的特定属性进行查询

我知道如何这样做:

@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s})

但我想知道是否有捷径……

解决方法

Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的 predefined finder methods

> Model.all
> Model.count
> Model.exists?
> Model.find
> Model.find_or_create_by
> Model.find_or_initialize_by
> Model.first
> Model.last

但是,它确实有一个通用的where method所以你这样说:

@lessons = Lesson.where(:user_id => current_user.id)

where也是可链接的(就像在较新版本的ActiveRecord中那样),这样你就可以通过链接更多的条件调用添加更多条件或指定排序.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...