[英]Rails + MongoID - Querying by attribute
我有这样的模型:
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
我得到了:
Lesson:Class的未定义方法`find_by_user_id'
如何通过MongoID中的特定属性进行查询?
我知道如何这样做:
@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s})
但我想知道是否有捷径......
Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的预定义finder方法 :
Model.all
Model.count
Model.exists?
Model.find
Model.find_or_create_by
Model.find_or_initialize_by
Model.first
Model.last
然而,它确实有一个通用的where
的方法 ,所以你这样说:
@lessons = Lesson.where(:user_id => current_user.id)
where
是可链接以及(就好像where
的的ActiveRecord的新版本),所以你可以添加更多的条件,或者通过链接多个标准调用指定的顺序。
从Mongoid 3.0.0版开始,您还可以:
@lessons = Lesson.find_by(user_id: current_user.id)
与where
相反,如果请求没有返回结果,它将引发Mongoid::Errors::DocumentNotFound
异常。 这是默认行为,但是如果将raise_not_found_error
配置选项设置为false
,则在这种情况下它将返回nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.