我有这样的模型:
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@H_403_4@我试图像这样查询:
@lessons_by_user = Lesson.find_by_user_id current_user.id@H_403_4@我得到了:
@H_403_4@undefined method `find_by_user_id’ for Lesson:Class@H_403_4@如何通过MongoID中的特定属性进行查询? @H_403_4@我知道如何这样做:
@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s})@H_403_4@但我想知道是否有捷径……
解决方法
Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的
predefined finder methods:
@H_403_4@> Model.all
> Model.count
> Model.exists?
> Model.find
> Model.find_or_create_by
> Model.find_or_initialize_by
> Model.first
> Model.last @H_403_4@但是,它确实有一个通用的
> Model.count
> Model.exists?
> Model.find
> Model.find_or_create_by
> Model.find_or_initialize_by
> Model.first
> Model.last @H_403_4@但是,它确实有一个通用的
where
method所以你这样说:
@lessons = Lesson.where(:user_id => current_user.id)@H_403_4@where也是可链接的(就像在较新版本的ActiveRecord中那样),这样你就可以通过链接更多的条件调用来添加更多条件或指定排序.