2012-03-17 34 views
5

我有这样一个模型:的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 

而且我越来越:

未定义的方法`find_by_user_id'用于课程:类

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

我知道如何做到这一点是这样的:

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

,但我想知道是否有捷径?

回答

9

Mongoid没有ActiveRecord的风格自动创建的查找方法,它仅支持有限的一组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是可链接以及(就像where中的ActiveRecord的新版本),所以你可以添加更多的条件,或者通过链接多个标准调用指定的顺序。

+0

太棒了。真的很高兴知道。 – 2012-03-17 06:17:18

3

由于Mongoid的版本3.0.0,你也可以这样做:

@lessons = Lesson.find_by(user_id: current_user.id) 

相反where,如果请求不返回结果,将提出一个Mongoid::Errors::DocumentNotFound例外。这是默认行为,但如果将raise_not_found_error配置选项设置为false,则在此情况下它将仅返回nil

来源:http://mongoid.org/en/mongoid/docs/querying.html

+1

感谢上面的“2 vs 3”文档修复。即使AR正在朝'find_by'方向发展,而不是'method_missing'中的所有讨厌'find_by_user_id'的东西。 – 2014-01-25 18:38:12