Hom*_*ith 6 ruby-on-rails mongodb 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
Run Code Online (Sandbox Code Playgroud)
我试图像这样查询:
@lessons_by_user = Lesson.find_by_user_id current_user.id
Run Code Online (Sandbox Code Playgroud)
我得到了:
Lesson:Class的未定义方法`find_by_user_id'
如何通过MongoID中的特定属性进行查询?
我知道如何这样做:
@lessons = Lesson.all(:conditions=>{:user_id=>current_user.id.to_s})
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有捷径......
mu *_*ort 10
Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的预定义finder方法:
Model.allModel.countModel.exists?Model.findModel.find_or_create_byModel.find_or_initialize_byModel.firstModel.last但是,它确实有一个通用的where方法,所以你这样说:
@lessons = Lesson.where(:user_id => current_user.id)
Run Code Online (Sandbox Code Playgroud)
where也是可链接的(就像where在较新版本的ActiveRecord中一样),因此您可以添加更多条件或通过链接更多条件调用来指定排序.
| 归档时间: |
|
| 查看次数: |
5176 次 |
| 最近记录: |