[英]Rails + MongoID - Querying by attribute
I have a model like this: 我有这样的模型:
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
And I am trying to query like this: 我试图像这样查询:
@lessons_by_user = Lesson.find_by_user_id current_user.id
And I am getting: 我得到了:
undefined method `find_by_user_id' for Lesson:Class
Lesson:Class的未定义方法`find_by_user_id'
How can I query by a specific attribute in MongoID? 如何通过MongoID中的特定属性进行查询?
I know how to do it like this: 我知道如何这样做:
@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s})
but I am wondering if there is a shortcut... 但我想知道是否有捷径......
Mongoid doesn't have the ActiveRecord style auto-created finder methods, it only supports a limited set of predefined finder methods : 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
However, it does have a general purpose where
method so you say this: 然而,它确实有一个通用的
where
的方法 ,所以你这样说:
@lessons = Lesson.where(:user_id => current_user.id)
where
is chainable as well (just like where
in newer versions of ActiveRecord) so you can add more conditions or specify the ordering by chaining more criteria calls. where
是可链接以及(就好像where
的的ActiveRecord的新版本),所以你可以添加更多的条件,或者通过链接多个标准调用指定的顺序。
Since the version 3.0.0 of Mongoid, you can also do: 从Mongoid 3.0.0版开始,您还可以:
@lessons = Lesson.find_by(user_id: current_user.id)
Contrary to where
, it will raise a Mongoid::Errors::DocumentNotFound
exception if the request returns no result. 与
where
相反,如果请求没有返回结果,它将引发Mongoid::Errors::DocumentNotFound
异常。 It's the default behavior, but if you set the raise_not_found_error
configuration option to false
, it will just return nil
in this case. 这是默认行为,但是如果将
raise_not_found_error
配置选项设置为false
,则在这种情况下它将返回nil
。
Source: http://mongoid.org/en/mongoid/docs/querying.html 资料来源: http : //mongoid.org/en/mongoid/docs/querying.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.