微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 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

我得到了:

undefined method `find_by_user_id’ for Lesson:Class

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

我知道如何这样做:

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

但我想知道是否有捷径……

解决方法

Mongoid没有ActiveRecord样式自动创建的finder方法,它只支持一组有限的 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也是可链接的(就像在较新版本的ActiveRecord中那样),这样你就可以通过链接更多的条件调用添加更多条件或指定排序.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐